2

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
});

But this behaves buggy sometimes. When I input some text very fast, I am getting results for input word with some last letters of the original input word omitted (may be some fault with browser). I want the ajax request to be sent when there is no input activity for a second, I mean, if I input text very fast and rest for a second (means I made the input). How can I do this?

Bill the Lizard
  • 386,424
  • 207
  • 554
  • 861
Alfred
  • 20,303
  • 60
  • 160
  • 239
  • An almost identical question has actually been asked already _today_: http://stackoverflow.com/questions/10830972/user-idle-time-while-typing-in-input – lanzz May 31 '12 at 11:01
  • You can see this http://stackoverflow.com/questions/1909441/jquery-keyup-delay – Zernel May 08 '13 at 02:53

3 Answers3

7

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.

Linus Thiel
  • 37,636
  • 9
  • 103
  • 101
3

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!
Andreas
  • 20,797
  • 7
  • 44
  • 55
1

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

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

<input onkeyup="function()">