Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AJAX: Delay for search on typing in form field [duplicate]

On my website I use JavaScript/AJAX to do the search and show results while the user is still typing.

HTML (body):

<form action="" method="post" accept-charset="utf-8">
    <p><input type="text" name="q" id="q" value="" onkeyup="doSearch(this.value)" /></p>
</form>

JavaScript (header):

function doSearch(text) {
    // do the ajax stuff here
    // call getResults.php?search=[text]
}

But this could cause a lot of requests coming to the server.

Thus I want to relieve the server by setting up a delay:

Whenever the onkeyup event is fired, the function doSearch() should show an "ajax loading graphic" and wait for 2 seconds. Only if the event is NOT fired again during these 2 seconds, the results should be fetched from the PHP file.

Is there any way to do this? Could you help me please? Thanks in advance!

like image 965
caw Avatar asked Oct 21 '11 12:10

caw


People also ask

How to delay the keyup() handler until the user stops typing?

Use a variable to store the timeout function. Then use clearTimeout() to clear this variable of any active timeout functions, and then use setTimeout() to set the active timeout function again.

How do you trigger an event in input text after quitting typing writing?

$('input#username'). keypress(function() { var _this = $(this); // copy of this object for further usage setTimeout(function() { $. post('/ajax/fetch', { type: 'username', value: _this. val() }, function(data) { if(!

How do you execute a function only after the user stops typing?

Executing a function after a certain amount of inactivity is known as debouncing. Debouncing can be helpful for many reasons. One of the most popular applications in web development is to execute a search or filter some results after a user has stopped typing text in a textbox.


3 Answers

var delayTimer;
function doSearch(text) {
    clearTimeout(delayTimer);
    delayTimer = setTimeout(function() {
        // Do the ajax stuff
    }, 1000); // Will do the ajax stuff after 1000 ms, or 1 s
}
like image 126
Mike Richards Avatar answered Oct 05 '22 13:10

Mike Richards


Simply setup the delayed invocation with setTimeout(), then remove it again on every event with clearTimeout()

HTML

<form action="" method="post" accept-charset="utf-8">
    <p><input type="text" name="q" id="q" value="" onkeyup="doDelayedSearch(this.value)" /></p>
</form>

Javascript

var timeout = null;

function doDelayedSearch(val) {
  if (timeout) {  
    clearTimeout(timeout);
  }
  timeout = setTimeout(function() {
     doSearch(val); //this is your existing function
  }, 2000);
}
like image 34
Jonas Høgh Avatar answered Oct 05 '22 12:10

Jonas Høgh


For this type of thing I tend to use a cunning little 'throttling' function created by Remy Sharp:

http://remysharp.com/2010/07/21/throttling-function-calls/

like image 26
Andy Hume Avatar answered Oct 05 '22 12:10

Andy Hume