Reputation: 4565
I am pulling out my hair on JQuery/JSON issue where the response of $.getJSON
function is not making sense.
So here is my Javascript code excerpt:
var jqxhr = $.getJSON("myPHPFunction.php", function() {
alert("success");
})
.success(function() { alert("second success"); })
.error(function() { alert("error"); })
.complete(function() { alert("complete"); });
The JSON returned by the PHP function is this:
{"sid":"12", "name":"somename", "email":"someemail"}
Full response:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head><title>Untitled Document</title><meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
</head>
<body> {"sid":"12", "name":"somename", "email":"someemail"}
</body>
</html>
When I run the script, I get a dialog box saying error
.
Several online validator have reported the JSON to be syntax-correct. Then why does JQuery fail? Note both the php and the script are in the same folder (on server) and same domain.
Upvotes: 0
Views: 179
Reputation: 2887
From the comments, you can't encapsulate the JSON in HTML markup. You'll need to ensure that the data returned ("View Source" is a good tool for verifying this) is pure JSON.
Upvotes: 3
Reputation: 47955
Your response must not contain any HTML!
Propberbly you also need to set the correct content type:
header("Content-Type: application/json");
echo('{"sid":"12", "name":"somename", "email":"someemail"}');
exit();
The code above should work.
Please note that you must not output any other code before the header line.
Upvotes: 1