I’m trying to fetch some JSON data from my server like so:
var a = $.ajax({
url: "data.json",
dataType: 'json',
data: null,
error: function(data) {
console.log("error");
},
success: function(data) {
console.log("success");
}
});
When I do this, the error function is called (error is printed to the console).
Curiously, though, when I examine a I see that the correct response text has been returned.
a
readyState: 4
responseText: "contents of data.json!"
status: 200
statusText: "OK"
What’s going on? Why isn’t the success callback firing if the request is succeeding?
Probably because the specific value being returned isnt in the type that you specified. The response itself is a success (as you see by viewing the details of “a”), but that is not the only deciding factor for whether succes or error is executed. You specified json as the “dataType” (return type), but received a string. For testing, thats fine, but as you see, things wont run as expected. If you dont specify the dataType option, jQuery will attempt to determine the content type returned by looking at the mime type and the content of the response. Its an error when they dont match up (as in your case).
UPDATE:
I realized I rambled in my explanation above. Although you seemed to fix the problem, let me elaborate again.
There were several possibilities for errors to occur in your situation. The important thing to understand is that if you set “dataType”, jQuery will attempt to parse the responseText with that type. If you do not set that option, it will guess and parse it accordingly (that means it will look at the MIME type) and parse it that way. If you specify the “dataType”, the responseText needs to be in the format of JSON. So if you specify “json”, but provide a string (in your case), jQuery parsing fails. If you don’t specify the “dataType” and jQuery guesses, the responseText needs to match the MIME type. So you can’t return a string when the MIME type is “application/json”. When things don’t match up, that’s when errors occur.
Hopefully that helps!