From what I’ve read the general solution to this is as follows:
var DataRequest = $.ajax({ /* ... */ });
and then DataRequest.abort() in the beforeSend ajax event. However, this results in NO requests being sent.
What I’m trying to achieve is to abort any ajax operations that are declared as DataRequest (for example), and allow only the latest request to proceed. Currently I have a button that when clicked starts a request and adds a loading spinner. If I click it many times, I just get a bunch of loading spinners filling up my page. How can I prevent this?
Here’s the relevant code:
beforeSend: function() {
$('<div class="grid"></div>')
.attr('id', 'loading')
.hide()
.insertBefore('#output')
.fadeIn();
},
success: function(data) {
$('#loading').hide(function () {
$(this).remove();
});
}
Here’s the pattern I use when I need to have multiple requests and only process the last:
Edit: I have wrapped this functionality up in a plugin-like method call here:
Cancel a jQuery AJAX call before it returns?