When I bring my server down and make an ajax request to it, firebug shows that the request is aborted a few seconds after making the request, and my success
handler gets called.
Why does the success handler get called, shouldn't it be the error handler? And how can I reliably detect that it wasn't actually a success?
CODE:
$.ajax({
url: url,
type: "POST",
data: data,
dataType: "json",
success:function(data, statusText, xhr){
//gets called on success, or even when server is down.
},
error: function(){
//called if server returns error, but not if it doesn't respond
}
});
UPDATE: This behavior is only on localhost, it happens when turning off my development server. I tested to see what happens when I try to reach the production server, but have my personal internet taken offline, and it just hangs, not calling success or error at all. Guess I should set the timeout property for that case.
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.
You can check when exactly it returns "success" : // If successful, handle type chaining if ( status >= 200 && status < 300 || status === 304 ) { ... // If not modified if ( status === 304 ) { statusText = "notmodified"; ... // If we have data } else { try { ...
Yes, it is deprecated in jQuery 1.8 onwards. You should use . done() and use . fail() to catch the errors.
Just use ajax.abort(); } //then you make another ajax request $. ajax( //your code here );
I think this is a bug (?) in the 1.4.2 version of jQuery.
I quote one comment from the jQuery documentation:
In 1.4.2 jquery doesn't call ajax error callback on timeout/connection error, to fix this: remove the trailing " || xhr.status === 0" from httpSuccess function
Make that if you do want to modify the jQuery code itself. Else you can check it in your success callback like I make here:
$.ajax({
type: "POST",
url: "http://madeUpServerthatdoesnotExist.com/index.php",
data: "id=1",
success: function(msg){
if(this.xhr().status === 0 ){
errorHandler();
}
else {
alert('Success');
}
},
error: errorHandler
});
function errorHandler(){
alert('Freakin error');
}
It seems to be tricky, please comment if you know about a better way!
EDIT: After researching, I'm not sure that this could be a bug in jQuery, will update the answer as soon as I get a clue
It looks like this bug was fixed in jQuery 1.4.3:
http://bugs.jquery.com/ticket/6060
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