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?
});
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.
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.
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;});
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