In my web page (built on the Django platform), I have some jQuery that requests server data via an ajax request. How do I prevent the error function from executing when I click away from the page before the ajax request has responded.
Here is my jQuery call:
$(document).ready(function() {
$.ajax( {
url:'/server/url/',
type: 'POST',
data: {some..data},
success:function(response) { do stuff with response },
error: function() {alert('error')}
});
How do I prevent the alert from happening when I click away from the page (to a new page)?
Define a global variable:
var ajaxcancel = false;
No you need to make that true if user closes the window:
$(window).bind("beforeunload", function() {
ajaxcancel = true;
});
And change the ajax error line to check for the value of that variable first:
...
error: function() {if (!ajaxcancel) 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