just a quick question about datepicker and json. I have this code:
var dates = {'2013/4/4':'some description' , '2012/6/6':'some other description'};
function date_propogate() {
console.log('in function');
$.getJSON('URL OF JSON', function(data) {
date_items = data.items;
console.log(date_items);
$.each(date_items, function(index, date_item) {
dates.push(date_item.sdate);
});
});
}
$(document).ready(function() {
date_propogate();
$('#datepicker').datepicker({
beforeShowDay: function(date) {
var search = date.getFullYear() + "/" + (date.getMonth() + 1) + "/" + (date.getDate());
if (dates[search]) {
return [true, 'highlight', dates[search] || ''];
}
return [false, '', ''];
}
});
});
The JSON page returns this:
{"items":[{"sdate":"2013-02-25","edate":"2013-02-27","cost":"200","id":"1"}]}
I have two dates which are static which display fine, but the date which is returned by: date_items.sdate is not loading, I am getting an error saying 'no method: push'.
Am I doing this correctly at all or is there a better way? As I'm assuming I can't do it with just php on the page because the js is loading before the php right?
Any help would be hugely appreciated.
You have dates declared as an object using {}, rather than an array using []. You can't call .push() on an object.
dates is an object and an object doesn't have a function called push. Arrays do have these functions.
Anyway, simply do this:
var dates = ['2013/4/4':'some description' , '2012/6/6':'some other description'];
Dates is not an array, so you can't push to it. You would need to define dates as an array
var dates = [{'2013/4/4':'some description'} , {'2012/6/6':'some other description'} ]
The above creates an array of objects.
Related
I'm trying to get the dhtmlx event calendar to work on my angularjs webapp. I'm still new to all this, and combining the calendar with angularjs and php+mysql (to get events from db), there is not that much info to be found on the combination of those 3.
This code initialises the calendar:
myAppProfile.directive('dhxScheduler', function() {
return {
restrict: 'A',
scope: false,
transclude: true,
template:'<div class="dhx_cal_navline" ng-transclude></div><div class="dhx_cal_header"></div><div class="dhx_cal_data"></div>',
link:function ($scope, $element, $attrs, $controller){
//default state of the scheduler
if (!$scope.scheduler)
$scope.scheduler = {};
$scope.scheduler.mode = $scope.scheduler.mode || "month";
$scope.scheduler.date = $scope.scheduler.date || new Date();
//watch data collection, reload on changes
$scope.$watch($attrs.data, function(collection){
scheduler.clearAll();
scheduler.parse(collection, "json"); <-- UNDEFINED
}, true);
//watch mode and date
$scope.$watch(function(){
return $scope.scheduler.mode + $scope.scheduler.date.toString();
}, function(nv, ov) {
var mode = scheduler.getState();
if (nv.date != mode.date || nv.mode != mode.mode)
scheduler.setCurrentView($scope.scheduler.date, $scope.scheduler.mode);
}, true);
//size of scheduler
$scope.$watch(function() {
return $element[0].offsetWidth + "." + $element[0].offsetHeight;
}, function() {
scheduler.setCurrentView();
});
//styling for dhtmlx scheduler
$element.addClass("dhx_cal_container");
//init scheduler
scheduler.init($element[0], new Date(), "month");
scheduler.load("agendaController.php");
}
}
});
Where I put the arrow, there it keeps turning up undefined. Don't know why it is, I do load in correct json data at the end, but even if the calendar is empty it should still work. I'm not really sure what I'm doing wrong..
Thanks!
I suspect that $watch triggers an event immediately after initialization before a value is assigned to the data attribute.
Try this:
$scope.$watch($attrs.data, function(collection){
if(collection) {
scheduler.clearAll();
scheduler.parse(collection, "json");
}
}, true);
Please help me with my problem in displaying JSON data into my view..
my script is:
$('#supplierId').change(function(){
$.get("{{ url('api/dropdown')}}",
{ option: $(this).val() },
function(data) {
var firstnameID = $('#firstnameID');
$.each(data, function(index, element) {
firstnameID.val(element.first_name);
});
});
});
and my JSON reply is:
{"id":7,"first_name":"John","last_name":"Doe"}
the thing is when i tried to:
alert(element.first_name);
it says UNDEFINED, but when I:
alert(element);
it gives me the value of the last name which is Doe.. my question is how can I then access the other values like the ID and the first name..
EDITED:
this is my route:
Route::get('api/dropdown', function(){
$input = Input::get('option');
$supllier = Supplier::find($input);
returnResponse::json($supllier->select(array('id','first_name','last_name'))
->find($input));
});
Please help me with this one, This is my first time using JSON so im a bit confuse on how this works.
Best Regards
-Melvn
Why are you using each? This should work:
$('#supplierId').change(function(){
$.get("{{ url('api/dropdown')}}",
{ option: $(this).val() },
function(data) {
var firstnameID = $('#firstnameID');
firstnameID.val(data.first_name);
});
});
Ok, give this a try..
Explicitly state that what you're expecting back from the server is JSON using the dataType option in get().
$('#supplierId').change(function()
{
$.get("{{ url('api/dropdown')}}",
{ option: $(this).val() },
function(data)
{
var firstnameID = $('#firstnameID');
$.each(data, function(index, element)
{
firstnameID.val(element.first_name);
});
},
'json' // <<< this is the dataType
);
});
Now you should be able to access the data using the dot syntax:
console.log("last_name: " + element.last_name);
console.log("first_name: " + element.first_name);
console.log("id: " + element.id);
I would add another few lines, just to check that you're getting back what you expect to see:
console.log("NEW ELEMENT"); // << indicator in the console for your reference
console.log(element); // << the whole "element"
I'm trying to get dates from my database and put them in an array where it would be stored in json.
MAIN.PHP
$('#datepicker').focus(function(){
$.ajax({
url: 'getDates.php',
data: "artist_name="+$('#name').html(),
dataType: 'json',
success: function(data)
{
}
});
})
getDates.php
$fullname = $_GET['artist_name'];
$result = mysql_query("SELECT .... FROM .... WHERE ... ='$fullname'")
$arraydates = array();
while($details = mysql_fetch_assoc($result)) {
array_push($arraydates, $details['event_date']);
}
echo json_encode($arraydates);
I've managed to put all the dates from the selected artist in the "arraydates".
I found this on google:
var unavailableDates = ["21-8-2013"];
function unavailable(date) {
dmy = date.getDate() + "-" + (date.getMonth() + 1) + "-" + date.getFullYear();
if ($.inArray(dmy, unavailableDates) == -1) {
return [true, ""];
} else {
return [false, "", "Unavailable"];
}
}
That's fine. But now I'm trying to get the results from the array (within getDates.php) and use them in the "main.php". So basically I want to use the data like above with "unavailableDates" array. (and thus, disable the specific dates within the jquery date picker).
Instead of having "unavailableDates", I have the "arraydates". I don't really know how can I use my array inside the "unavailable" function.
I'm not really good with json, actually it's my first time I used json. So could anyone please help me with that?
you can use jquery:
//...
success: function(data){
var arrayLength=data.length;
for(var i=0;i<arrayLength;i++){
if(unavailable(data[i]){
//your code here
}
}
}
//...
The ajax will return $arraydates in a JSON format. Use parse.JSON(returned value)
for example
success: function(data)
{
var unavailableDates = parse.JSON(data);
//Your code ....
}
Hope that helped.
How do I submit an array from dojo to php.
I'm submitting these values:
["a", "b", "c"]
Here's what I got so far:
btn_send.onclick(function(){
var name_array = name_looper();
console.log(name_array);
dojo.xhrPost({
url: "dojo_phpform.php",
content: {names: name_array},
load: function(result) {
var x = dojo.byId('results');
x.innerHTML = result;
}
});
});
function name_looper(){
var names = dojo.query('input[type=text]');
var name_array = [];
names.forEach(function(element, index, array){
name_array[index] = dojo.attr(element, 'value');
});
return name_array;
}
I tried to echo $_POST['names'] from the php file(dojo_phpform.php) and it didn't return any errors. It seems like the array isn't actually submitted. The only thing that's returned is the last item in the array. What do I do?Please help, Thanks in advance!
I just tested this with grails and php. In grails I have no problem getting an array submitted through a dojo xhrPost : I retrieve the array properly parsed with all its values as expected.
If I post :
dojo.xhrPost({
content : {
names : ['foo', 'bar']
},
url : "mygrailscontroller"
});
I get an array param on the other side. Which proves the problem hasn't to be solved on the dojo side, but on the php side.
In php, if a form input has a variable of type array, its name parameter has to be set with square brackets, like : "names[]" rather than "names".
So... in your case the solution is not to flatten the array into a string (sorry), but to name your array argument with brackets. So it would be :
dojo.xhrPost({
content : {
"names[]" : ['foo', 'bar']
},
url : "myphpcontroller"
});
As far as I've been able to see, dojo's xhr functions don't support it. I'm using a helper function to "flatten" parameters myself.
_flattenXhrParams: function(params)
{
var newParams = {};
for(var key in params)
{
if(dojo.isObject(params[key]))
{
for(var innerKey in params[key])
{
newParams[key + "[" + innerKey + "]"] =
params[key][innerKey];
}
}
else if(dojo.isArray(params[key]))
{
for(var i = 0, l = params[key].length; i < l; i++)
{
newParams[key + "[]"] = params[key][i];
}
}
else
{
newParams[key] = params[key];
}
}
return newParams;
}
It's butt ugly, I know, and obviously only works on one dimensional arrays/objects. In your case, you'd do:
dojo.xhrPost({
url: "dojo_phpform.php",
content: _flattenXhrParams({names: name_array}),
load: function(result) {
var x = dojo.byId('results');
x.innerHTML = result;
}
});
.. and you'd get POST parameters like names[]=a&names[]=b&names[]=c. For objects, you'd get names[somekey]=a&names[otherKey]=b etc. PHP handles both nicely.
I'm pretty sure the values of the content object only take strings. If you want to submit an array, you'd have to turn it into JSON and then json_decode it on the server.
I am trying to post a group of arrays using the jQuery post method, but I am having trouble getting the value of the arrays. How can I get the values of the array that I have sent?
If somebody could help me i would be grateful....
Here is what i have done:
$(document).ready( function()
{
$("#submit_info").click (
function()
{
var batchArr= new Array();
batchArr=arrPush('batch');
var facultyArr= new Array();
facultyArr=arrPush('faculty');
var levelArr= new Array();
levelArr=arrPush('level');
var sectionArr= new Array();
sectionArr=arrPush('section');
var shiftArr= new Array();
shiftArr=arrPush('shift');
$.post("server_side/college_info_insert.php",{
batchArr:batchArr,
facultyArr:facultyArr,
levelArr:levelArr,
sectionArr:sectionArr,
shiftArr:shiftArr
}, function(data)
{
alert(data);
});
}
);
function arrPush(opt)
{
var Arr= new Array();
Arr.push($("#"+opt+"_1").val());
var count= $("#"+opt).val();
var i=0;
for(i;i<=count;i++)
{
if(i==0)
{
Arr.push($("#txt"+opt).val());
}
else
{
Arr.push($("#txt"+opt+i).val());
}
}
return Arr;
}
}
);
How can I get the array values in the next page "college_info_insert.php" ??
okay, so this is actually a really common issue. It's unclear that you can't just send an array as-is from javascript to PHP and have it recognized.
The problem is that PHP doesn't know how to read in multiple values from a POST request - typically things like that require the PHP author to use brackets like: varname[].
So, basically you must send variables as strings. Using JSON you can send even complicated objects as strings to PHP using a single variable name. Typically you'd use JSON.stringify or something along those lines - but if you have a simple array you might not even need it.
Here's a full example of the problem/solution, found using jquery and $.post:
Asume you have a file myurl.php:
<?php
print_r($_POST);
?>
And in a separate file (or the console), you try:
var myarray = Array('some','elements','etc');
var mydata = {postvar1: 'string', postvar2: myarray};
$.post('myurl.php', mydata, function(response) {
alert("response: " + response);
});
This doesn't work! The result is that postvar2 only contains "etc".
The solution is force the array into a JSON string that can be decoded from PHP.
var myarray = Array('some','elements','etc');
var json_array = $.map(myarray,function(n) {
return '"'+n+'"';
});
var mydata = {postvar1: 'string', postvar2: '['+json_array+']' };
$.post('myurl.php', mydata, function(response) {
alert("response: " + response);
});
ON the PHP side you now must use: json_decode($_POST['myarray']); to get your results in a proper array.
Note, this example assumes very simple strings or numbers in your array. If you have complex objects, you will need to use a JSON.stringify function which will take care of extra quotes, escaping special characters, etc.
Not sure if i understood the question but wouldn't something like this work
if (isset($_POST['batchArr'])) {
$batchArr = $_POST['batchArr'];
// Then populate your html here e.g
echo $batchArr[0];
}