Skip to content

Abort A Previous Ajax Request In jQuery

Last updated on October 19, 2021

When using Ajax there will be chances, 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

<input id="searchbox" name="searchbox" type="text">
<div id="data">&nbsp;</div>

JQuery

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 a new request to the server. That is it, simple and straightforward isn’t it.

0 0 votes
Article Rating
Subscribe
Notify of
guest

2 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments