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:
JavaScript
x
27
27
1
var filterCandidates = function(form){
2
//Previous request needs to be aborted.
3
var request = $.ajax({
4
type: 'POST',
5
url: '/echo/json/',
6
data: {
7
json: JSON.stringify({
8
count: 1
9
})
10
},
11
success: function(data){
12
if(typeof data !== 'undefined'){
13
jQuery('.count').text(data.count)
14
console.log(data.count);
15
}
16
}
17
});
18
};
19
20
if(jQuery('#search').length > 0){
21
var form = jQuery('#search');
22
jQuery(form).find(':input').change(function() {
23
filterCandidates(form);
24
});
25
filterCandidates(form);
26
}
27
HTML:
JavaScript
1
6
1
<form id="search" name="search">
2
<input name="test" type="text" />
3
<input name="testtwo" type="text" />
4
</form>
5
<span class="count"></span>
6
Advertisement
Answer
JavaScript
1
19
19
1
var currentRequest = null;
2
3
currentRequest = jQuery.ajax({
4
type: 'POST',
5
data: 'value=' + text,
6
url: 'AJAX_URL',
7
beforeSend : function() {
8
if(currentRequest != null) {
9
currentRequest.abort();
10
}
11
},
12
success: function(data) {
13
// Success
14
},
15
error:function(e){
16
// Error
17
}
18
});
19