Here is my code:
$("input").on('keydown', function(){
$.ajax({
url : '/files/tags_autoplete.php',
dataType : 'JSON',
success : function (tags) {
$("ul").html(tags.output);
}
});
});
My code suggests some tags (the ones that have a matched substring with what the user has written so far) to user as an autoplete box when he is typing his tags.
What's my problem? My current code sends a new ajax request per each keydown. For example, if the user writes something
, my script sends 9 ajax requests which seems like a nightmare.
Anyway, how can I handle that? I mean do I need to implement a delay for sending? Something like "don't send the request until 1 sec after last character inserted"? or is there any better idea?
Here is my code:
$("input").on('keydown', function(){
$.ajax({
url : '/files/tags_autoplete.php',
dataType : 'JSON',
success : function (tags) {
$("ul").html(tags.output);
}
});
});
My code suggests some tags (the ones that have a matched substring with what the user has written so far) to user as an autoplete box when he is typing his tags.
What's my problem? My current code sends a new ajax request per each keydown. For example, if the user writes something
, my script sends 9 ajax requests which seems like a nightmare.
Anyway, how can I handle that? I mean do I need to implement a delay for sending? Something like "don't send the request until 1 sec after last character inserted"? or is there any better idea?
Share Improve this question asked Sep 22, 2016 at 19:11 Martin AJMartin AJ 6,70712 gold badges71 silver badges137 bronze badges 2- You might consider jQuery UI autoplete. It has your requested functionality built in. jqueryui./autoplete. It might not be worth using just for autoplete, but it's worth a look. – Jason P Commented Sep 22, 2016 at 19:32
- @JasonP Thank you for the link you provided .. but I seen that before .. and yes exactly as you said, using it just for autoplete isn't affordable. though I heard we can download every part of jQuery UI we need (for example, we can download only autoplete part) – Martin AJ Commented Sep 22, 2016 at 20:11
1 Answer
Reset to default 9You could create a simple throttle mechanism
$("input").on('keydown', function(){
clearTimeout( $(this).data('timer'); )
var timer = setTimeout(function() {
$.ajax({
url : '/files/tags_autoplete.php',
dataType : 'JSON',
success : function (tags) {
$("ul").html(tags.output);
}
});
}, 500);
$(this).data('timer', timer);
});