Page 1 of 1
Can you delay this Ajax Search?
Posted: Tue Oct 28, 2014 10:18 am
by simonmlewis
Code: Select all
function precheck(str)
{
if (str=="")
{
document.getElementById("txtHint").innerHTML="";
return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("srcHint").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","/presearch.php?q="+str,true);
xmlhttp.send();
}
We have issues on one of our web sites that use this script, as it checks the database on every "keyup". And images it loads are from another source.
Can this be set to run after a delay of so many milliseconds? So you start typing but when you stop, after say, 2 seconds, it then runs?
Re: Can you delay this Ajax Search?
Posted: Tue Oct 28, 2014 11:56 am
by Celauran
I'd start by checking that the user has entered more than X characters (x could be 2, 3, 4.. see what works best for you). Then you want to wrap your trigger in a timeout.
Code: Select all
var delay = (function() {
var timer = 0;
return function(callback, ms) {
clearTimeout (timer);
timer = setTimeout(callback, ms);
};
})();
$('#some_element').on('keyup', function(e) {
delay(function() {
// AJAX callback goes here
}, 100);
});
Re: Can you delay this Ajax Search?
Posted: Tue Oct 28, 2014 11:59 am
by simonmlewis
Yes - I think all the above would be good.
What is #some_element'?
I'm assuming it's important as so far it's not doing anything.
Re: Can you delay this Ajax Search?
Posted: Wed Oct 29, 2014 5:56 am
by Weirdan
Actually it's possible to augment the initial function in run time here:
Re: Can you delay this Ajax Search?
Posted: Wed Oct 29, 2014 6:00 am
by simonmlewis
Sorry how - where??
Re: Can you delay this Ajax Search?
Posted: Thu Oct 30, 2014 5:31 am
by simonmlewis
I've been reading this, but I don't understand how to "plug it in" to my code.
http://stackoverflow.com/questions/1909 ... eyup-delay
Re: Can you delay this Ajax Search?
Posted: Thu Oct 30, 2014 7:22 am
by Celauran
I've already given you a jQuery example and Weirdan showed you how you could accomplish the same with your existing code. Where are you stuck?
Re: Can you delay this Ajax Search?
Posted: Thu Oct 30, 2014 7:27 am
by simonmlewis
I don't know where that code of Weirdan goes - I'm not a jQuery expert at all. I can spot things and make adjustments, but plugging in bits to existing jQuery stuff is out of my skillset.