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