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

2

9

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?

Adriel answered 8/11, 2010 at 7:24 Comment(0)
P
5

Assuming you are using jQuery UI Autocomplete:

  1. You can specify the minimum length of string before starts searching. (default is 3 I guess)
  2. You can also specify the delay between last keystroke and ajax call. Usually 2-300ms should do.
  3. AjaxQueue might help you to clean some stuff. Dunno how (I never need it), but worth a shot :)
Personalty answered 8/11, 2010 at 7:40 Comment(0)
A
21

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 );
            }
        }));
    }
});
Applicant answered 3/10, 2012 at 17:16 Comment(1)
Just before the success/error callback ends, adding $element.data( "jqXHR", null ); will avoid aborting a completed AJAX request.Digitate
P
5

Assuming you are using jQuery UI Autocomplete:

  1. You can specify the minimum length of string before starts searching. (default is 3 I guess)
  2. You can also specify the delay between last keystroke and ajax call. Usually 2-300ms should do.
  3. AjaxQueue might help you to clean some stuff. Dunno how (I never need it), but worth a shot :)
Personalty answered 8/11, 2010 at 7:40 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.