Reputation: 8706
I've started the following skeleton for an ajax/post/update function I'm wanting to write in javascript (using jquery):
$.post("/gallery/resize",
function (data) {
alert(data);
alert(data.complete);
if (data.complete) {
alert("done");
} else {
alert("blah");
}
},
"json"
);
And the response script on the server is:
$return['complete'] = 'complete';
header('Content-type: application/json');
echo json_encode($return);
exit;
The FireBug console shows that I get a JSON string in response - but the value of data.complete is 'undefined'. Here is the string from the server as reported by the FireBug (I also have a corresponding value/data pair under the JSON tab under the XHR display in the console):
{"complete":"complete"}
Any pointers on what I might've missed...
I am working on a localhost server - apache on ubuntu - if that makes a difference?
Upvotes: 2
Views: 5243
Reputation: 31
JSON data is like a javascript array. So you should access it the same.
Therefore, in the code you provided, you should access the entry "complete" this way instead:
data.items[0].complete
That should do the trick.
You may look here for further jQuery/JSON information.
Upvotes: 1
Reputation: 8706
oh boy - turns out that I was a bit too trusting of the power of jQuery - I was missing a parameter in the $.post() method which may be optional unless you want to specify the other things.
the odd thing is that the callback works without the preceding data parameter being set - but it freaks out when you want to set the datatype (and must have the data and callback set).
So - the correct code for what I want would be:
$.post("/gallery/resize", "",
function (data) {
alert(data);
alert(data.complete);
if (data.complete) {
alert("done");
} else {
alert("blah");
}
},
"json"
);
Upvotes: 5
Reputation: 900
I'm not sure how jQuery parses JSON data, but it may be the JSON string is being evaluated incorrectly. If you enter {"complete":"complete"}
in the FireBug console, it is interpreted as a block statement rather than an object literal (the "complete"
property name is evaluated as a label). This is fixed by evaluating either ({"complete":"complete"})
or {complete:"complete"}
, or using JSON.parse
on {"complete":"complete"}
. The quickest way to fix this would be to remove the "json"
parameter from the $.post
call and parse the data your self, like so:
$.post("/gallery/resize",
function (data) {
var obj;
if (JSON.parse) {
obj = JSON.parse(data);
} else {
obj = eval("(" + data + ")"); // obligatory eval() warning
}
if (data.complete) {
alert("done");
} else {
alert("blah");
}
}
);
Incidentally, if you're debugging with Firebug, always try to use console.log
instead of alert
- it doesn't interrupt execution of the JS, and it gives much more informative JSON serialization than [object Object]
Upvotes: 2
Reputation: 1038830
Try this:
header('Content-Type: application/json');
$return = array('complete' => 'complete');
echo json_encode($return);
exit;
Upvotes: 1