3

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
  • 398,270
  • 210
  • 566
  • 880
Alfred
  • 21,058
  • 61
  • 167
  • 249
  • 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

8

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
  • 38,647
  • 9
  • 109
  • 104
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
  • 21,535
  • 7
  • 47
  • 56
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()">