I have read through many, many Q&A of the same issue, but none have my specific issue (at least not that I could find).
I have a php script that echos back a json string
header('Content-Type: application/json');
echo $result;
JSON returned (checked with JSONLint and is valid):
{"Announcement":{"ID":1,"Type":1,"Text":"This is a test Albums announcement.","TimeStart":"1969-12-31","TimeEnd":"1969-12-31"}}
And a web jquery script that reads the json:
$.ajax({
type : "GET",
url : "http://b***s.net/S****s/GetAnnouncements.php?callback=?",
data : {get_param : "Announcement"},
dataType : "json",
error : function(jqXHR, textStatus, errorThrown) {alert(errorThrown); alert(textStatus);},
success : function(data) {alert('success');
$.each(data, function(index, element) { alert('here');
$("#announcements-list").append("<li><a id='announcements-a-" + element.ID + "' href='#announcement-details'><p>" + element.Type + ": " + element.Text + "</p></a></li>");
$("#announcements-a-" + element.ID).bind('click', function() {Announcements.AnnouncementID = element.ID;});
});
$("#announcements-list").listview('refresh');
}
});
success:
is never called. And error:
returns a textStatus
of "parsererror"
and errorThrown
is "Error: jQuery1830649454693285679_1359620502896 was not called"
callback=?
to the url to work around the cross-domain issue.header('Content-Type: application/json');
to the php, and it returns NO html.data: "json"
as some answers say, but that still returns a parsererror
Your server and client scripts do not complement each other. You have two options:
Make your server side script return JSON:
Content-Type: application/json
{"Announcement":{"ID":1}}
And omit the callback parameter:
$.ajax({
type : "GET",
url : "http://example.com/feed/json.php",
dataType : "json"
});
Make your server side script return JSONP i.e. JSON wrapped in a callback function:
Content-Type: application/javascript
jQuery_xxxxxxxx({"Announcement":{"ID":1}});
And change datatype to jsonp:
$.ajax({
type : "GET",
url : "http://example.com/feed/json.php",
dataType : "jsonp"
});
Note that jQuery silently appends &callback=jQuery_xxxxxxxx
to the URL for such requests.
The server should use the callback name specified in the URL. You can do something like this:
echo sprintf(
"%s(%s);",
isset($_GET["callback"]) ? $_GET["callback"] : "void",
json_encode($data)
);