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