Robert MacGrogan
Robert MacGrogan

Reputation: 357

How to tell if JQuery Error Means Call Was Interrupted

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!

Upvotes: 6

Views: 912

Answers (2)

Robert MacGrogan
Robert MacGrogan

Reputation: 357

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!');
       }
    }
});

Upvotes: 8

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324770

Reading the documentation, I would hazard a guess that your error handler should be like this:

error(xhr, textStatus, errorThrown) {
    if( textStatus != "abort") {
        alert("Error!");
    }
}

Upvotes: 3

Related Questions