Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to tell if JQuery Error Means Call Was Interrupted

Tags:

jquery

Suppose I have a somewhat long-running jQuery Ajax call (say 5 seconds) as follows:

$.ajax({
    url: '/LongCall',
    type: 'POST',
    async: true,
    cache: false,
    datatype: 'json',
    success: function(data) {
      alert('Success!');
    },
    error(xhr, textStatus, errorThrown) {
      alert('Error!');
    }
});

Now suppose while waiting for my five second process to run the user grows impatient and decides to hit some sort of navigation on my page. What happens in the above call is the user gets the Error alert when he clicks a link.

I do want the error alert to display if there really is an error, but if all that happened is that the user decided to navigate away, I do not want the error alert to display. How can I do this?

In other words, is there some value I can check (xhr.status maybe?) that will tell me that the error that occurred is simply that the process was interrupted so I can know to ignore the error?

Thanks!

like image 548
Robert MacGrogan Avatar asked Mar 04 '13 22:03

Robert MacGrogan


1 Answers

As near as I can tell, the best way to do this is to check xhr.readyState in your error handler. Any value less than 4 indicates that the process is still running so this means something is happening in the browser to interrupt it.

You also want to call xhr.abort() to attempt to stop the ajax process so the user doesn't have to wait for it to finish before the navigation actually happens, though for me the call to xhr.abort() does not actually speed things up.

$.ajax({
    url: '/LongCall',
    type: 'POST',
    async: true,
    cache: false,
    datatype: 'json',
    success: function(data) {
      alert('Success!');
    },
    error(xhr, textStatus, errorThrown) {
       if (xhr.readyState < 4) {
           xhr.abort();
       }
       else {
           alert('Error!');
       }
    }
});
like image 86
Robert MacGrogan Avatar answered Nov 11 '22 10:11

Robert MacGrogan