Why does calling $ .ajax for json data cause an error callback when the HTTP status code is "200 OK"?

I have the following ajax request:

jQuery.ajax({ async: true, type: "GET", url: url, data: data, dataType: "json", success: function(results){ currentData = results; }, error: function(xhr, ajaxOptions, thrownError){ if (xhr.status == 200) { console.debug("Error code 200"); } else { currentData = {}; displayAjaxError(xhr.status); } } }); 

For some reason, the error callback is called an event, although the http status code is 200, i.e. request is ok. Why is this?

+7
json jquery ajax error-handling
source share
3 answers

The problem may be that the json data returned from the url was incorrect. When the server really returns something, the http status code is 200. But this does not mean that the data is valid json. Verify that json string data is correctly generated.

I respond to my invitation because I have learned it. I did not escape the "-quote" character in my json data, which led to very strange behavior. Fortunately, the double quote character is pretty much the only character to be avoided from data transmitted via JSON. (More on this issue: Where can I find the list of escape characters needed for my ajax JSON return type? )

+10
source

Does your callback return a page with Content-type: application/json ? If not, this may be the reason.

+1
source

I test a lot with the file: urls instead of using a web server. My JSON code will always have the wrong MIME type. To take care of this, I use the following code:

 $(document).ready( function (){ myData = {}; $.ajax({ type: "GET", // url: "json.php?fn=jsonData.json", // with Apache url: "jsonData.json", // As a file:/// URL contentType: "application/json; charset=utf-8", data: myData, beforeSend: function(x) { if(x && x.overrideMimeType) { x.overrideMimeType("application/json; charset=UTF-8"); } }, dataType: "json", success: function(returnData){ $("#jsonData").html("Success:"+returnData.tag); }, error: function(returnData) { $("#jsonData").html("Error:"+returnData.tag); } }); } ); 

This will result in the correct MIME type for the JSON data.

0
source

All Articles