Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I have the previous ajax calling stopped when I raise a new one?

I'm using jQuery's autocomplete, but have found a performance-related issue - if I input 'abc', it will be scanning by 'a', by 'ab', and by 'abc', at a once, how can I stop the previous 'a', 'ab' when ajax calling is doing searching by 'abc'?

The similar case is: I use jQuery DataTables, and want to do some searching like, I typed something to search (call search web method), and clicked button - 'Search' 3 times at a once, or changed search text just when I clicked 'Search', and raise a new search, how can I stop the previous useless ajax calling?

like image 293
Elaine Avatar asked Nov 08 '10 07:11

Elaine


People also ask

How can I cancel old AJAX request?

To abort a previous Ajax request on a new request with jQuery, we can call the abort method on the request object. For instance, we can write: const currentRequest = $. ajax({ type: 'GET', url: 'https://yesno.wtf/api', }) $.

How can I make AJAX call only once?

Use the . one() function : Attach a handler to an event for the elements. The handler is executed at most once per element.

Is there a way to limit the time an AJAX call will run?

Not possible. It's the browser's responsibility.


1 Answers

JQuery's $.ajax returns a xmlHttpRequest object which can be canceled via its native method .abort()

$("#search").autocomplete({
    minLength: 3,
    delay: 300, // this is in milliseconds
    json: true,
    source: function(request, response){
        // New request 300ms after key stroke
        var $this = $(this);
        var $element = $(this.element);
        var previous_request = $element.data( "jqXHR" );
        if( previous_request ) {
            // a previous request has been made.
            // though we don't know if it's concluded
            // we can try and kill it in case it hasn't
            previous_request.abort();
        }
        // Store new AJAX request
        $element.data( "jqXHR", $.ajax( {
            type: "POST",
            url: "foo.php",
            dataType: "json",
            success: function( data ){
                response( data );
            }
        }));
    }
});
like image 119
Bruno Lange Avatar answered Sep 17 '22 18:09

Bruno Lange