Skip to content Skip to sidebar Skip to footer

Keyup(function()) Ajax Request Delay - Jquery

I have a jQuery Ajax request, that I want to call with text input, and so I nested it inside keyup(function(). This works fine. $('#text_box').keyup(function() { //AJAX REQUEST })

Solution 1:

It sounds as if you get results from a previous ajax call. Use a timer with setTimeout and clearTimeout.

var timer = null;

$("#text_box").keyup(function() {
  if(timer) {
    clearTimeout(timer);
  }

  timer = setTimeout(someFunction, someDelay);
});

Where someFunction is a function which does your ajax call and someDelay is the delay you want to wait before doing the call, after the user has typed, in ms.

Solution 2:

As you are already using jQuery you could use the debounce plugin from Ben Aleman.

Example from the page

// Bind the not-at-all debounced handler to the keyup event.
  $('input.text').keyup( text_1 );

  // Bind the debounced handler to the keyup event.
  $('input.text').keyup( $.debounce( 250, text_2 ) ); // This is the line you want!

Solution 3:

omg. for somebody who will search in 2014...

functionsendAjax() {
    setTimeout(
        function() {
            $.ajax({
                url: "url.php",
                type: "POST",
                data: data,
                success: function(data) {
                    $("#result").html(data);
                }
            });
        }, 2000);
}

<input onkeyup="function()">

Post a Comment for "Keyup(function()) Ajax Request Delay - Jquery"