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)
})
Written by M. Oguz
Related protips
2 Responses
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
·
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Jquery
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#