Ahnaf
Ahnaf

Reputation: 159

How to auto execute search function with javascript?

I am trying to search from mysql database . i want the search function be executed when the user stop typing. i have gone through javascript documentation in w3school and tried:

var timer = null;
 document.getElementById("search-key")
  .addEventListener("keyup", function(event) {
    event.preventDefault();
    clearTimeout(timer); 
    timer = setTimeout(ajaxcall(), 500000);

});

ajaxcall() is my search function and search-key is the id of the textbox. My another confusion is does these keyup/keydown functions work with barcode scanner?

Upvotes: 0

Views: 234

Answers (1)

user01
user01

Reputation: 901

Two problems, each with setTimeout:

setTimeout's first parameter is a function to call, not the result of the function.

ie: setTimeout(ajaxcall,ms) and not setTimeout(ajaxCall(),ms).

Note the parentheses, which will execute the function on the spot and pass the returned value to setTimeout (probably not what you want, unless you are returning a function from ajaxcall)

setTimeout's second parameter is milliseconds until execution.

You specify 500,000 milliseconds. This is 8 minutes and 20 seconds. Seems like a long time to wait before issuing a call.

var ajaxcall = function(){
  console.log('AJAX SENT');
}

var timer = null;
document.getElementById("search-key")
  .addEventListener("keyup", function(event) {
    event.preventDefault();
    clearTimeout(timer);
    timer = setTimeout(ajaxcall, 500);

  });
<input id="search-key"/>

Upvotes: 1

Related Questions