JQuery UI Autocomplete: how to start an asynchronous process and exit it before it ends?

I am using jQuery UI autocomplete to create a search interface.

I defined a user-defined function that returns search results and updates them automatically as you press the keys, sometimes this custom function does not end until the next key is pressed (ie, it is still processed by "Wash" when I already wrote "Washi" ( on the way to writing "Washington").

I would like each call to the autocomplete event "source" to cancel the previous function ("Erase") and launch a new function (Washi). With the following call cancellation function (Washi) and start function (Washin), etc.

How it's done?

+2
jquery jquery-ui jquery-ui-autocomplete
source share
1 answer

You should do something like this:

var lastXhr; $( "#myAutocomplete" ).autocomplete({ source: function( request, response ) { if (lastXhr) lastXhr.abort(); lastXhr = $.getJSON( "search.php", request, function( data, status, xhr ) { if ( xhr === lastXhr ) { response( data ); } }); } }); 

lastXhr var holds the most recent xhr request. If there is one set and the source function is called, it aborts the lastXhr request and creates a new one. When an ajax request is returned, if you make sure it matches lastXhr, if not, it does not call the response() function.

+3
source share

All Articles