Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to cancel an ajax request in Django when new page is requested

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)?

like image 502
Steve Walsh Avatar asked Jan 21 '26 20:01

Steve Walsh


1 Answers

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'); }
...
like image 125
Hossein Avatar answered Jan 23 '26 19:01

Hossein



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!