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 event though the http status code is 200 ie. the request is OK. Why is this?
According to the AJAX model, web applications can send and retrieve data from a server asynchronously without interfering with the display and the behavior of the existing page. Many developers use JSON to pass AJAX updates between the client and the server.
Many pages send AJAX requests to a server. Because this relies on the cooperation of the server and the network between the client and the server, you can expect these AJAX errors: Your JavaScript program receives an error response instead of data; Your program has to wait too long for the response.
The callback function is a function that is executed when the Ajax call is completed. The callback function is passed two parameters: the response from the Ajax call and the status of the Ajax call. The callback function should be defined as a function and not as a property of an object.
AJAX success is a global event. Global events are triggered on the document to call any handlers who may be listening. The ajaxSuccess event is only called if the request is successful. It is essentially a type function that's called when a request proceeds.
The problem might be that the json data returned from the url is malformed. When the server actually returns something, the http status code is 200. But that doesn't mean that the data is proper json. Check that the stringified json data returned is correctly formed.
I'm answering my own guestion because I learned this the hard way. I hadn't escaped a "-quote character in my json data. This resulted in very odd behaviour. Luckily the double quote character is pretty much the only character that needs to be escaped from data delivered via JSON. (More on this issue: Where can I find a list of escape characters required for my JSON ajax return type?)
Does your callback return a page with Content-type: application/json
? If not, that could well be the reason.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With