2

Good night I would like to know if it is possible in the code below to insert this function in ajax. I would like to only submit the search after 2 seconds of the user finishing typing, replacing the "onkeyup".

PS:This is for an Ajax Live Search.

function pesquisar(value) {
$("#results").show();
$.ajax({
    type:'post', 
    url:'/classes/searchfetch.php', 
    data: {s:value},    
    success: function (data){
        $("#results").html(data);
    },
}); };

I would be very grateful if you could help me.

2 Answers2

1

Can use a timer that would also get canceled if user continues within the 2 seconds

var timer;

$('input').keyup(function(){
   // clear prior timeout
   clearTimeout(timer);
   // create new one
   timer = setTimeout(pesquisar, 2000)

})
charlietfl
  • 170,828
  • 13
  • 121
  • 150
1

In order to start a search after the user finished typing, we can start a timer when the user releases a key and stop it if he pressess one. If the difference between these two events is more than 2 seconds our event will be fired. Assuming your input has id as inp

 var timer;

//Start a timer on keyup event
$('#inp').on('keyup', function () {
  //add loading indicator
  $('#results').html("<img src='loading.gif'>");
  clearTimeout(timer);       // clear timer
  timer = setTimeout(pesquisar, 2000);
});


$('#inp').on('keydown', function () {
  clearTimeout(timer);       // clear timer if user pressed key again
});

/call ajax function when user finished typing
function pesquisar(value) {
$("#results").show();
$.ajax({
    type:'post', 
    url:'/classes/searchfetch.php', 
    data: {s:value},    
    success: function (data){
        $("#results").html(data);
    },
}); };
diagold
  • 493
  • 1
  • 7
  • 28
Shubham Khatri
  • 270,417
  • 55
  • 406
  • 400