tags:

views:

117

answers:

1

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.

+1  A: 

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

Matias
this seems to work
Kyle