This answer to a related question is what worked for me:
https://stackoverflow.com/a/10701856/5114
Note the first line where the @grr says: "Using ajaxSetup is not correct"
You can adapt his answer to add your own function to window if you want to call it yourself rather than use window.onbeforeunload
as they do.
// Most of this is copied from @grr verbatim:
(function($) {
var xhrPool = [];
$(document).ajaxSend(function(e, jqXHR, options){
xhrPool.push(jqXHR);
});
$(document).ajaxComplete(function(e, jqXHR, options) {
xhrPool = $.grep(xhrPool, function(x){return x!=jqXHR});
});
// I changed the name of the abort function here:
window.abortAllMyAjaxRequests = function() {
$.each(xhrPool, function(idx, jqXHR) {
jqXHR.abort();
});
};
})(jQuery);
Then you can call window.abortAllMyAjaxRequests();
to abort them all. Make sure you add a .fail(jqXHRFailCallback)
to your ajax requests. The callback will get 'abort' as textStatus
so you know what happened:
function jqXHRFailCallback(jqXHR, textStatus){
// textStatus === 'abort'
}