tags:

views:

63

answers:

5

Is there any easy way to abandon all outstanding jQuery AJAX requests? My application is capable of pulling off a lot of simultaneous requests, so race becomes problematic. I've put in hackish solutions (namely, putting in a flag that is checked upon request completion), but it would be much nicer to get a global stop all outstanding requests function.

+1  A: 

I would say store all ajax requests in an array. When you need to kill then just loop through all values in array and call abort(). When a request is completed or aborted just pop from the array.

spinon
+1  A: 

XMLHttpRequest has an abort() function. $.ajax lets you get your hands on the xhr object. keep a record of all outstanding xhr's and go xhr.abort() for any you want to terminate.

Scott Evernden
+3  A: 

Assign every ajax request as an element of an array:

var requests = [];

requests.push( $.ajax({
    type: 'POST',
    url: '...',
    success: successfunc
    });
);

And to kill:

$.each( requests, function( i, v ){
    v.abort();
})
Ken Redler
Thanks. This seems to have done the trick. I chose a slightly different implementation that I detail [here](http://stackoverflow.com/questions/3313059/jquery-abandon-all-outstanding-ajax-requests/3313954#3313954)
Steven Xu
+1  A: 

as the others have said, use the .abort() method. However, this ONLY works on calls within the same domain. once you enter into cross-site calls (with jsonp), then the .abort() method is delegated to null, so wont actually fire/work.

worth noting as this caused me endless debugging time many a small moon ago :)

jim

jim
Cool information, thanks for that heads up.
Anders
anders - pleasure... (tho' check the latest status on IE as it was mainly the XMLHttpRequest in IE that had been an issue when trying to make it browser agnostic in my case). i seem to remember that the abort 'timeout' is set to 0 on x-site calls. anyway.. :)
jim
A: 

Based on Ken Redler's solution, I put this in my initialization:

window.requests = []
$.ajaxSetup({
  beforeSend: function(xhr){
    var new_request_list = [xhr]
    $.each(window.requests, function(k,v){
      if(v.readyState != 4) new_request_list.push(v)
    })
    window.requests = new_request_list
  }
})

I put in the snippet with new_request_list just to keep the global variable from getting crowded with completed XHR objects.

Steven Xu
I would put the cleanup function in the `$.ajaxSetup` or `xhr.onreadystatechange`, but I'm concerned that this would interfere with whatever jQuery does on its own. This solution seems to work fine.
Steven Xu