views:

20

answers:

1

I've got a custom javascript autocomplete script that hits the server with multiple asynchronous ajax requests. (Everytime a key gets pressed.)

I've noticed that sometimes an earlier ajax request will be returned after a later requests, which messes things up.

The way I handle this now is I have a counter that increments for each ajax request. Requests that come back with a lower count get ignored.

I'm wondering: Is this proper? Or is there a better way of dealing with this issue?

Thanks in advance,

Travis

+2  A: 

You can store a "global" currentAjaxRequest, which holds the structure of the last XHR request. Then you can abort the current request when you make a new one.

For example:

var currentAjaxRequest = null;

function autoCompleteStuff() {
    if(currentAjaxRequest !== null) {
        currentAjaxRequest.abort();
    }

    currentAjaxRequest = $.get(..., function(...) {
        currentAjaxRequest = null;

        ...
    });
}

To avoid naming conflicts, wrap that in an anonymous, instantly-executed function, if needed.

strager