When maintaining my (old) web app I found out that error handling stopped working, probably already some time ago. Here is my old code which was working:
$.ajax({
url: this.url,
type: 'post',
data: jsonsendobject,
dataType: 'json',
crossDomain: true, // comment this out when not in test mode from foreign webapp
xhrFields: { withCredentials: true }, // comment this out when not in thest mode from foreign webapp
}).done(function(data, textStatus, jqXHR) {
// do something after it worked
}).fail(function(jqXHR,textStatus,errorThrown) {
console.log(JSON.stringify(jqXHR));
// now always returns: {"readyState":0,"status":0,"statusText":"error"}
});
Now jqXHR always returns 0, even if the server obviously sends a 500 status code.
I searched a lof of questions here at stackoverflow but most of them were asked around 2011 and the quality of answers unfortunately is bad. Here are different opinions I read:
- jquery as of 2.0 (of 3.0) does not support the jqXHR object anymore. It is returned for compatibility reasons but status is always 0.
- jqXHR object is empty when used with HTTP 2.0
- HTTP status codes don't work if dataType is "json" (or "jsonp")
- HTTP status codes do not work if it is crossDomain (or a local web app)
But if I read the documentation (https://api.jquery.com/jquery.ajax) I cannot find evidence that one of these answers is correct,
I understand that I could probably do something like this
$.ajax({
statusCode: {
404: function() {
alert( "page not found" );
}
}
});
But I'd rather like to get the status code and decide after (together with other parameters) what to do about it.
What is the working, non-deprecated way of getting the status code within the .fail() call?