Abort previous ajax request on new request
var currentRequest = null;
currentRequest = jQuery.ajax({
type: 'POST',
data: 'value=' + text,
url: 'AJAX_URL',
beforeSend : function() {
if(currentRequest != null) {
currentRequest.abort();
}
},
success: function(data) {
// Success
},
error:function(e){
// Error
}
});
var filterCandidates = function(form){
//Previous request needs to be aborted.
var request = $.ajax({
type: 'POST',
url: '/echo/json/',
data: {
json: JSON.stringify({
count: 1
})
},
success: function(data){
if(typeof data !== 'undefined'){
jQuery('.count').text(data.count)
console.log(data.count);
}
}
});
return request;
};
var ajax = filterCandidates(form);
save in a variable, and then, before sending second time, check its readyState
and call abort()
if needed
a variation on the accepted answer and adopted from a comment on the question - this worked great for my application....
using jQuery's $.post()....
var request = null;
function myAjaxFunction(){
$.ajaxSetup({cache: false}); // assures the cache is empty
if (request != null) {
request.abort();
request = null;
}
request = $.post('myAjaxURL', myForm.serialize(), function (data) {
// do stuff here with the returned data....
console.log("returned data is ", data);
});
}
Call myAjaxFunction() as many times as you like and it kills all except the last one (my application has a 'date selector' on it and changes price depending on the days selected - when someone clicks them fast without the above code, it is a coin toss as to if they will get the right price or not. With it, 100% correct!)