tags:

views:

24

answers:

1

Hello,

i have a function which returns a certain ammount of data triggered in AJAX when typping.

But, as soon as i type "long" string like "hello my name is", it launches a single request each time i type a key (10request at a single time and it takes 5 seconds to get 1 request response).

How to avoid that please ? (i don't want to use .onblur)

$(document).ready(function()
    {
      $('.search input[type="submit"]').hide();

      $('#search_keywords').keyup(function(key)
      {
        if (this.value.length >= 2 || this.value == '')
        {
          $('#loader').show();
          $('#jobs').load(
            $(this).parents('form').attr('action'),
            { query: this.value + '*' },
            function() { $('#loader').hide(); }
          );
        }
      });
    });

Thank you ;)

+2  A: 

I tend to set a timer on that keyup event, like this:

$('#search_keywords').keyup(function() {
  clearTimeout($.data(this, 'timer'));
  $(this).data('timer', setTimeout($.proxy(search, this), 500));
});
function search()  {
  if (this.value.length >= 2 || this.value == '') {
    $('#loader').show();
    $('#jobs').load(
      $(this).parents('form').attr('action'),
      { query: this.value + '*' },
      function() { $('#loader').hide(); }
    );
  }
}

This breaks your search into another function, and we're just delaying 500ms between hitting a key and firing that search function. If you type another letter, the 500ms timer resets with the clearInterval(), so quick typing won't trigger 20 events, only once you pause a half second will it fire. The $.proxy() part is so that this is correct when the setTimeout() executes.

Nick Craver
Exactly how I'd do it, too. I might add an extra option to do the query after every *x* keystrokes, regardless of the delay, but that's starting to get complicated :-)
Dean Harding
That is perfect : one question, if the user type : hello. It'll trigger the request for "H", then wait 500ms, then trigger for "He" .....OR it search only "H", then "Hello" (assuming he typed this in 500ms) ?
Tristan
@Tristan - It'll trigger once they stop typing for 500ms, so if they type "hello" quickly (never 500ms or more between keystrokes) it'll do *one* search for "hello". As another example if you typed "hel" and paused for over a half second, it would search for that, make sense?
Nick Craver
Got it thank you, that is awesome. ;)
Tristan