jQuery $.ajax calls success handler when reuqest fails because of browser reloading

Posted by Martin on Stack Overflow See other posts from Stack Overflow or by Martin
Published on 2010-12-29T10:00:43Z Indexed on 2010/12/29 10:54 UTC
Read the original article Hit count: 224

Filed under:
|
|

I have the following code:

 $.ajax({
          type: "POST",
          url: url,
          data: sendable,
          dataType: "json",
          success: function(data) {

               if(customprocessfunc)
                   customprocessfunc(data);
         },

          error: function(XMLHttpRequest, textStatus, errorThrown){
                    // error handler here
                }
        });

I have a timer which makes AJAX requests often. If I do not receive anything in 'data', I show an error message to the user - it means, something wnet bad on the server.

The problem is when user reloads the page while the AJAX call is in progress. I can see in the firebug that the AJAX call fails (URL is colored red and no HTTP status is displayed) so I expect that jQuery will stop the reuqest or at least go to the error handler. But it goes to the success handler and passes null in the 'data' variable.

As a result, when user reloads the page, sometimes he can see my big red message about unknown error (because data is null).

Is there any way to make jQuery abort the request on complete reloading all at least not to call my success function? I have no way to know in the success handler why the data is null - did it came empty from the server or the call was aborted because of reload.

© Stack Overflow or respective owner

Related posts about jQuery

Related posts about AJAX