Failed to return / process JSON in JQuery $ .get ()
I have an issue with returning / processing JSON data when calling $ .get () function. Here's the code:
JQuery:
$.get("script.php?",
function(data) {
if (data.status) {
alert('ok');
} else {
alert(data.error);
}
},'json');
PHP
if ($r) {
$ret = array("status"=>true);
} else {
$ret = array("status"=>false,"error"=>$error);
}
echo json_encode( $ret );
So this is the code. But the answer is always accepted as a string in jquery. data.status and data.error undefined
.
a source to share
Your PHP script needs to set the Content-type
response header to application/json
, for example:
header('Content-type: application/json');
Alternatively, you can tell jQuery to return JSON using a parameter dataType
. Or just use getJSON
that does exactly that. :-)
Edit Sorry, just noticed: youpass the parameter dataType
to get
. My suggestion is to take a close look at the response text: is it really JSON? ( This site can help there.) From your quoted PHP it looks like it should be, but if there was any other way out before or after ...
a source to share