optimized search using ajax and keypress

Posted by ooo on Stack Overflow See other posts from Stack Overflow or by ooo
Published on 2010-06-12T12:50:43Z Indexed on 2010/06/12 12:52 UTC
Read the original article Hit count: 199

Filed under:
|
|
|

i have the following code as i want to search a database as a user is typing into a textbox. This code below works fine but it seems a little inefficient as if a user is typing really fast, i am potentially doing many more searches than necessary. So if a user is typing in "sailing"

i am searching on "sail", "saili", "sailin", and "sailing"

i wanted to see if there was a way to detect any particular time between keypresses so only search if user stops typing for 500 milliseconds or something like this.

is there a best practices for something like this?

$('#searchString').keypress(function(e) {

    if (e.keyCode == 13) {

        var url = '/Tracker/Search/' + $("#searchString").val();
        $.get(url, function(data) {
            $('div#results').html(data);
            $('#results').show();
        });
    }
    else {

        var existingString = $("#searchString").val();
        if (existingString.length > 2) {
            var url = '/Tracker/Search/' + existingString;
            $.get(url, function(data) {
                $('div#results').html(data);
                $('#results').show();
            });
        }
    }

© Stack Overflow or respective owner

Related posts about jQuery

Related posts about AJAX