How can i stop my AJAX call so I can start a new one?

December 26, 2017

The use case for this was a search functionality that was triggered on keyup.  That said, the more a user typed the ajax call would fire again and again till the search had queued so many ajax calls that the final result may or may not be the last ajax call to complete.  Plus the user should essentially be told the search restarted and is not wasting more time finishing searches that were no longer relevant.

It’s actually just a small addition using a variable i’m naming search_xhr. If there is is an active search happening, you can run the search_xhr.abort(); function to kill the process before it finishes. This is useful when ever you started to get something you wanted from a service that is no longer relevant based on a user interaction.


var search_xhr = null;

function api_search(options){
    if( search_xhr != null ) {
	search_xhr = null;

    //visual start/restart queue can happen here

    search_xhr = $.ajax({
        type: "GET", 
        url: '[search_api_url]',
        data: options,
        dataType: "json",
        success: function(ajaxdata){
            //visual finish queue can happen here
            search_xhr = null;

Stay in Touch!

Subscribe to our newsletter.

Solutions Architecture

browse through our blog articles

Blog Archive