Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ignoring old multiple asynchronous ajax requests

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

like image 812
Travis Avatar asked Feb 28 '23 09:02

Travis


1 Answers

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.

like image 171
strager Avatar answered Mar 06 '23 15:03

strager