2

I have REST webservices that supports long polling. if server has any new data it'll send to me, if I made Jquery Ajax request. If there is no update from server, the request will be in pending state. Now I want to cancel that request if user log out suddenly. I tried like

var request=$.ajax({
--------
-
-------
});

request.abort();

But I am getting error here, since request didn't received any data from server (cause still in pending state). So it is 'null'.

How can I cancel that Ajax request ?

Rajeev
  • 312
  • 3
  • 10
  • 1
    Everyone seems to imply what you are doing is correct, see potential duplicate here: http://stackoverflow.com/questions/446594/abort-ajax-requests-using-jquery You can also set a timeout on the request, if you want to abort after a set period of time. – DrLivingston Feb 12 '14 at 21:03

1 Answers1

0

Abort is regarded as an error by jquery, so you'll need to check your jqXHR's statusText in the fail handler to see if it has been aborted and handle accordingly.

Here's code to illustrate:

var jqXHR = $.ajax({
    url: '...'
});

// jqXHR.abort() is regarded as an error, so your logic for detecting
// it should go in the fail handler.  Here's how you could set this up:
jqXHR.fail(function(args) {
    if (jqXHR.statusText == 'abort') {
        console.log('AJAX aborted');
        return;
    }

    // Other error processing goes here.

});

// If pending, abort AJAX call
if (jqXHR.state() == 'pending') {
    jqXHR.abort();
}
huwiler
  • 915
  • 9
  • 9