Friday, May 10, 2024
 Popular · Latest · Hot · Upcoming
45
rated 0 times [  47] [ 2]  / answers: 1 / hits: 72827  / 11 Years ago, tue, october 8, 2013, 12:00:00

I have a function that runs an AJAX call on the change of an input.


But, there is a chance that the function will be fired again before the previous ajax call has completed.


My question is, how would I abort the previous AJAX call before starting a new one?
Without using a global variable. (See answer to a similar question here)


JSFiddle of my current code:


Javascript:


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

if(jQuery('#search').length > 0){
var form = jQuery('#search');
jQuery(form).find(':input').change(function() {
filterCandidates(form);
});
filterCandidates(form);
}

HTML:


<form id="search" name="search">
<input name="test" type="text" />
<input name="testtwo" type="text" />
</form>
<span class="count"></span>

More From » ajax

 Answers
9
 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
}
});

[#75151] Monday, October 7, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kaitlynnb

Total Points: 402
Total Questions: 96
Total Answers: 109

Location: Trinidad and Tobago
Member since Fri, May 8, 2020
4 Years ago
kaitlynnb questions
;