Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ajax sent on "keyup" duplicates results when fast typing!

This is my Ajax:

$("form[0] :text").live("keyup", function(event) {

    event.preventDefault();
    $('.result').remove();
    var serchval = $("form[0] :text").val();

    if(serchval){

        $.ajax({

            type: "POST",
            url: "<?= site_url('pages/ajax_search') ?>",
            data: {company : serchval},
            success: function(data) {

                var results = (JSON.parse(data));
                console.log(results);

                if(results[0]){
                    $.each(results, function(index) {
                        console.log(results[index].name);
                        $("#sresults").append("<div class='result'>" + results[index].name + "</div>");
                    });
                }
                else {
                    $("#sresults").append("<div class='result'>לא נמצאו חברות</div>");
                }
            }
        });
    }
});

When I type slowly (slower then a letter per second) I get the results correct, when I type faster I get 2 times the same results

example:
slow typing: res1 res2 res3
fast typing: res1 res2 res3 res1 res2 res3

Also, any advice on improving the code would be welcome!

like image 449
ilyo Avatar asked Jul 13 '11 11:07

ilyo


People also ask

What does Keyup return?

The keyup event is fired when a key is released. The keydown and keyup events provide a code indicating which key is pressed, while keypress indicates which character was entered. For example, a lowercase "a" will be reported as 65 by keydown and keyup , but as 97 by keypress .

What is Keyup in Ajax?

The keyup event occurs when a keyboard key is released. The keyup() method triggers the keyup event, or attaches a function to run when a keyup event occurs.

How do I delay Keyup?

In this article, we will see how to use keyup with a delay in jQuery. There are two ways to achieve the same: Approach 1: Using the keypress(), fadeIn(), delay() and fadeOut() methods in the jQuery library and clearTimeout() and setTimeout() methods in native JavaScript.

What is Keyup in JavaScript?

The keyup() is an inbuilt method in jQuery which is used to trigger the keyup event whenever User releases a key from the keyboard. So, Using keyup() method we can detect if any key is released from the keyboard. Syntax: $(selector).keyup(function)


2 Answers

Thats what is happening (pseudocode):

When you're typing slow:

.keyup1
.remove1
//asynchronous ajax1 request takes some time here...
.append1
.keyup2
.remove2
//asynchronous ajax2 request takes some time here...
.append2

When you're typing fast:

.keyup1
.remove1
//asynchronous ajax1 request takes some time here...
//and keyup2 happens before ajax1 is complete
.keyup2
.remove2
.append1
//asynchronous ajax2 request takes some time here...
.append2
//two results were appended _in a row_ - therefore duplicates

To solve duplicates problem, you would want to make your results removing/appending an atomic operation - using .replaceWith.

Build results HTML block first as string and then do the .replaceWith instead of .remove/.append:

var result = '';
for (i in results) {
    result += "<div class='result'>" + results[i].name + "</div>";
}

$("#sresults").replaceWith('<div id="sresults">' + result + '</div>');

Another problem (not related to duplicates) may be that older result overwrites newer which arrived earlier (because AJAX is asynchronous and server may issue responses not in the same order it receives requests).

One approach to avoid this is attaching roundtrip marker (kind of "serial number") to each request, and checking it in response:

//this is global counter, you should initialize it on page load, global scope
//it contains latest request "serial number"
var latestRequestNumber = 0;

$.ajax({
    type: "POST",
    url: "<?= site_url('pages/ajax_search') ?>",
    //now we're incrementing latestRequestNumber and sending it along with request
    data: {company : serchval, requestNumber: ++latestRequestNumber},
    success: function(data) {
        var results = (JSON.parse(data));
        //server should've put "serial number" from our request to the response (see PHP example below)
        //if response is not latest (i.e. other requests were issued already) - drop it
        if (results.requestNumber < latestRequestNumber) return;
        // ... otherwise, display results from this response ...
    }
});

On server side:

function ajax_search() {
    $response = array();

    //... fill your response with searh results here ...

    //and copy request "serial number" into it
    $response['requestNumber'] = $_REQUEST['requestNumber'];

    echo json_encode($response);
}

Another approach would be to make .ajax() requests synchronous, setting async option to false. However this may temporarily lock the browser while request is active (see docs)

And also you should definitely introduce timeout as algiecas suggests to reduce load on server (this is third issue, not related to duplicates nor to request/response order).

like image 98
lxa Avatar answered Oct 06 '22 06:10

lxa


You should involve some timeout before calling ajax. Something like this should work:

var timeoutID;

$("form[0] :text").live("keyup", function(event) {

    clearTimeout(timeoutID);

    timeoutID = setTimeout(function()
    {
       $('.result').remove();
       var serchval = $("form[0] :text").val();

       if(serchval){

           $.ajax({

               type: "POST",
               url: "<?= site_url('pages/ajax_search') ?>",
               data: {company : serchval},
               success: function(data) {

                   var results = (JSON.parse(data));
                   console.log(results);

                   for (i in results)
                   {
                       console.log(results[i].id);
                       $("#sresults").append("<div class='result'>" + results[i].name + "</div>");
                   }
               }
           });
       }
   }, 1000); //timeout in miliseconds
});

I hope this helps.

like image 38
algiecas Avatar answered Oct 06 '22 05:10

algiecas