Last Updated: February 25, 2016
·
1.126K
· arcv

Prevent double ajax request when using input's onchange

Problem is when you put a search box and want to show suggestions to user after every input. Browser will make ajax request everytime user presses key.

To prevent this, you can use setTimeout and clearTimeout functions.

var request = null;
$("input[name=q]").on('keydown', function(e){
    clearTimeout(request);
    that = this;

    request = setTimeout(function(){
        $.get("/search", {q: $(that).val()}, function(resp){
            console.log(resp);
        })
    }, 300)
})

2 Responses
Add your response

or just store the request and use the "abort()" method if it exists :-)

over 1 year ago ·

Except xhr.abort() still allows a request to be initiated. Timeout + abort() is probably the most comprehensive solution.

over 1 year ago ·