When using Ajax there will be changes ,where you will need to cancel the Ajax call. I found Aborting is useful while building a search as you type feature and I would abort the previous search and request a new Ajax search each time they typed a new letter. Since their old word has changed to a new word and therefore new meaning, completing the old request is having no purpose or reason since the new word is an entirely different meaning.
Luckily jQuery has made this almost easy as you can see by my example below.
Html
1 2 |
<input id="searchbox" name="searchbox" type="text" /> <div id="data"></div> |
JQuery
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
jQuery(document).ready(function(){ var currentRequest = null; jQuery('#searchbox').keyup(function() { var text = jQuery(this).val(); currentRequest = jQuery.ajax({ type: 'POST', data: 'search_text=' + text, url: 'AJAX_URL', beforeSend : function() { if(currentRequest != null) { currentRequest.abort(); } }, success: function(data) { jQuery('#data').html(data).show(); } }); }); }); |
Now you can type something for each keyup()
event it will cancel the previous Ajax request and it will make new request to the sever.That is it, Simple and straightforward isn’t it.
This does not work for some reason – better solution: https://stackoverflow.com/a/16751040/3273588