Stop pending Ajax requests using jQuery

I use the direct search function on my website (rails). Every time there is a keystroke, I submit a form. But if the user enters several characters, several search queries are sent to the server. I was wondering if there is a way to stop previous (unprocessed) requests. I want only the last request to be successfully processed.

I know that there is an abort () method that interrupts the ajax request, but I no longer have control over the previous request, so I cannot cause an interrupt while doing this. Maybe I'm something wrong here.

Is anyone

thank

Punite

+3
source share
1 answer

Ajax jQuery. - "debouncing" : http://benalman.com/code/projects/jquery-dotimeout/examples/debouncing/ ( ). , ; . .

:

var lastRequest;
$("input").keypress(function(){
    if (lastRequest){
        lastRequest.abort();
        lastRequest = null;
    }
    lastRequest = $.ajax({type: "POST", url: "some.php", data: "your=data&goes=here"});
});

: Ajax jQuery

Bootnote: "lastRequest" .

+5

Source: https://habr.com/ru/post/1764411/


All Articles