Share Article To

Some time we want to show auto search results just underneath the auto search box. After each character write into the text box we want to get the result from the database related to the characters present in search text box and for that we have to do AJAX call. In this case if someone wrote 4 characters then 4 ajax call will be fired and from all these ajax calls last response will be taken as a search result. Sometime it may not be correct. Because sometime before fired Ajax call can give response after the later fired ajax call, in this case we may have inconsistent data. And to solve this issue we have to abort the previously fired ajax calls. Now the question is How to stop a AJAX call before calling the same again? Below sample code will solve this problem.


<input id=”search-box” name=”serch-box” type=”text” />
<div id=”result”></div>

<script>
jQuery(document).ready(function(){
var currentRequest = null;
jQuery(‘#search-box’).keyup(function() {
var text = jQuery(this).val();
currentRequest = jQuery.ajax({
type: ‘POST’,
data: ‘search_text=’ + text,
url: ‘AJAX_URL_HERE’,
beforeSend : function()    {
if(currentRequest != null) {
currentRequest.abort();
}
},
success: function(data) {
jQuery(‘#result’).html(data).show();
}
});
});
});
</script>

One thought on “How to stop a AJAX call before calling the same again

Leave a Reply

Your email address will not be published. Required fields are marked *