jquery ui autocomplete: how to cancel slow ajax request after text input loses focus jquery ui autocomplete: how to cancel slow ajax request after text input loses focus ajax ajax

jquery ui autocomplete: how to cancel slow ajax request after text input loses focus


$.ajax returns a jqXHR object and that object exposes the abort method of the underlying XMLHttpRequest object. So, you just need to stash the jqXHR and abort the request at the right time. Something like this perhaps:

source: function(request, response) {    var $this = $(this);    var $element = $(this.element);    var jqXHR = $element.data('jqXHR');    if(jqXHR)        jqXHR.abort();    $element.data('jqXHR', $.ajax({        // ...        complete: function() {            // This callback is called when the request completes            // regardless of success or failure.            $this.removeData('jqXHR');            // And dismiss the search animation.            response({});        }    });}

And then you'd want some stuff on #city:

$('#city').blur(function() {    var $this = $(this);    var jqXHR = $(this).data('jqXHR');    if(jqXHR)        jqXHR.abort();    $this.removeData('jqXHR');});

There is a brief blur/focus sometimes during the autocompleter's normal operation but that only happens when when someone chooses something from the list; there shouldn't be a $.ajax request running when that happens so we don't need to worry about it. If I'm wrong then you can kludge around it by using a timer inside the blur handler and cancelling the timer in a focus callback (you could store the timer-ID in another .data() slot too).

I haven't tested this but I'm pretty sure it will work.