0

When I browse, in stackoverflow itself I could find so many questions like this. Still asking.. as I couldnt get any idea.

if ($.trim(location).length > 2) {
    var randomNum = Math.floor(Math.random() * 9999999999999);
    var url = "/mobile/App/GetLocations?noCache=" + randomNum + "&h="
            + location;

    $('#' + smartFillBoxId).empty();
    $('#' + smartFillBoxId).hide();

    $.ajax({
        url:url
    }).done(
            function (data) {
                selectedLocation = htmlData = "";
                var count = 0;
                results = eval('(' + data + ')').results;
                $('#' + smartFillBoxId).show();
                $.each(eval('(' + data + ')').results, function (index, results) {
                    htmlData = formatLocation(results,count);
                    $('#' + smartFillBoxId).append(
                            "<li><a href='#' onclick='addSelectedValue(\""
                                    + elementName + "\",\""
                                    + count + "\",\""
                                    + smartFillBoxId + "\")' >"
                                    + htmlData
                                    + "</a></li>");
                    count++;
                });
            });
}


Scenario:
1. Have a text box.
2. In the text box user will type minimum 3 characters.
3. Ajax will be executed with those characters
4. A smartfill box will list with appended values (as list)

Works fine when i am typing slowly in the text box.
But the smartfill data will list two/three times when I am typing fast in the text box.
The ajax call function is binded to 'onkeyup' event.

4
  • If you're trying to create your own autocomplete textfield, you might be better served by using one that's already well-developed. Commented Aug 13, 2013 at 13:51
  • Oh, if there is any other way you can tell me. I am using 'jQuery_v1.7.2' Commented Aug 13, 2013 at 13:54
  • To what event are you binding this code? Commented Aug 13, 2013 at 13:56
  • 1
    to begin with, you should be using onkeydown because onkeyup will make your search appear to be slow. Secondly, you should be using a throttle that prevents the ajax request from being sent until the user stops typing for n milliseconds. Look at the source for jQuery UI Autocomplete for more information. Commented Aug 13, 2013 at 14:12

2 Answers 2

1

It is firing multiple times because you are binding to the key press event and each event will fire the ajax. You should throttle this to prevent the ajax call from firing until the user stops typing. Something like this:

var timeoutId = null;
$("#t1").keydown(function () {
    if (timeoutId != null)
        window.clearTimeout(timeoutId);
    timeoutId = window.setTimeout(updateIt, 500);
});

function updateIt()
{
    // Do your code here
}

See this fiddle for a simplistic example: http://jsfiddle.net/2gqZv/

Sign up to request clarification or add additional context in comments.

Comments

0

You could have a flag that indicates a new ajax call shouldn't be initiated until the last one completes:

var isFetching = false;

$.ajax({
    url:url
}).done(
        function (data) {
         if(isFetching == false){ //CHECK TO SEE IF WE SHOULD INTERRUPT PREVIOUS AJAX CALL
            isFetching = true; //FLIP FLAG TO ENSURE NO OTHER CALLS INTERFERE
            selectedLocation = htmlData = "";
            var count = 0;
            results = eval('(' + data + ')').results;
            $('#' + smartFillBoxId).show();
            $.each(eval('(' + data + ')').results, function (index, results) {
                htmlData = formatLocation(results,count);
                $('#' + smartFillBoxId).append(
                        "<li><a href='#' onclick='addSelectedValue(\""
                                + elementName + "\",\""
                                + count + "\",\""
                                + smartFillBoxId + "\")' >"
                                + htmlData
                                + "</a></li>");
                count++;
            });

            isFetching = false; //CALL COMPLETED

        });
      }

}

EDIT Since you are binding to the keypress handler, you could instead do something like:

var isFetching = false;

$('#myelement').keypress(function(){
if(isFetching == false){
    isFetching = true;

    $.ajax({
        url:url
        }).done(
        function (data) {
         //ALL YOUR GLORIOUS CODE
         isFetching == false;
       }
   }
});

Not tested, apologies if my braces are off.

2 Comments

This seems not working. I added as follows. var isFetching = false;console.log("starting..."); But 'starting...' is printing two times when i am typing fast..!!. And that means this is some problem in the event onkeyup i think !!
I didn't put together you were binding to the keypress event. You could use the flag variable like I demonstrate, but use it to determine if you should fire your keypress event handler instead.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.