Abort new AJAX request before completing the previous one

JavascriptAjaxJquery

Javascript Problem Overview


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>

Javascript Solutions


Solution 1 - Javascript

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

Solution 2 - 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);
            }
        }
    });
    return request;
};

var ajax = filterCandidates(form);

save in a variable, and then, before sending second time, check its readyState and call abort() if needed

Solution 3 - Javascript

a variation on the accepted answer and adopted from a comment on the question - this worked great for my application....

using jQuery's $.post()....

var request = null;

function myAjaxFunction(){
     $.ajaxSetup({cache: false}); // assures the cache is empty
     if (request != null) {
        request.abort();
        request = null;
     }
     request = $.post('myAjaxURL', myForm.serialize(), function (data) {
         // do stuff here with the returned data....
         console.log("returned data is ", data);
     });
}

Call myAjaxFunction() as many times as you like and it kills all except the last one (my application has a 'date selector' on it and changes price depending on the days selected - when someone clicks them fast without the above code, it is a coin toss as to if they will get the right price or not. With it, 100% correct!)

Solution 4 - Javascript

if(typeof window.ajaxRequestSingle !== 'undefined'){
  window.ajaxRequestSingle.abort();
}

window.ajaxRequestSingle = $.ajax({
  url: url,
  method: 'get',
  dataType: 'json',
  data: { json: 1 },
  success: function (data) {
    //...
  },
  complete: function () {
    delete window.ajaxRequestSingle;
  }
});

Solution 5 - Javascript

Try this code

var lastCallFired=false;

var filterCandidates = function(form){
    
    if(!lastCallFired){
    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);
            }
        }
    });
        setInterval(checkStatus, 20);
        
    }
   
};

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

var checkStatus = function(){
        if(request && request.readyState != 4){
            request.abort();
        }
    else{
        lastCallFired=true;
    }
};

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionCharliePrynnView Question on Stackoverflow
Solution 1 - JavascriptSiva.NetView Answer on Stackoverflow
Solution 2 - JavascriptRomkoView Answer on Stackoverflow
Solution 3 - JavascriptApps-n-Add-OnsView Answer on Stackoverflow
Solution 4 - JavascriptArthur ShlainView Answer on Stackoverflow
Solution 5 - JavascriptMurali MurugesanView Answer on Stackoverflow