Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detecting that a jQuery.ajax call failed because the page is reloading?

Tags:

jquery

ajax

I do lots of $.ajax calls, and I handle errors from them in a way that throws up a message. I find that if an ajax call is in progress while the page gets reloaded, e.g. click refresh, or navigate to another URL, then my in-progress ajax calls trigger their error callbacks.

How can I tell the difference between a real error, and a call that aborted because the page got reloaded?

$.ajax(...)
.success(...)
.error(function(jqXHR) {
  // jqXHR.status == 0 means either failed to contact server,
  // or aborted due to page reload -- how can I tell the difference?
});
like image 971
kdt Avatar asked Feb 22 '12 15:02

kdt


People also ask

How to handle timeout in ajax?

Code snippet:$. ajax({ url: "test. php", error: function(){ //Error code }, success: function(){ //Success code } timeout: 5000 // sets timeout to 5 seconds }); The success function is executed if the request succeeds.

What causes Ajax fail?

Many pages send AJAX requests to a server. Because this relies on the cooperation of the server and the network between the client and the server, you can expect these AJAX errors: Your JavaScript program receives an error response instead of data; Your program has to wait too long for the response.


1 Answers

Add an unload handler, which sets a flag to true. Then, inside the error handler, you can check this flag, and do something appropriate.

Example:

var unloading = false;
$.ajax(...) ...
 .error(function(jqXHR) {
    if (unloading) return; // Ignore errors caused by navigating away
    // Now, check for real errors ..
});
$(window).unload(function() {unloading = true;});
like image 122
Rob W Avatar answered Nov 15 '22 22:11

Rob W