Question

I have the following script:

  $(document).ready(function(){
    $('#input').keyup(function(){
        sendValue($(this).val());   

    }); 

});
function sendValue(str){
    $.post("ajax.php",{ sendValue: str },
    function(data){
        $('#display').html(data.returnValue);
    }, "json");

}

The script is used in an instant search type scenario (like Google), so it is sending quite a few select requests to the server as the user types in the textbox (although I already use pconnect so there are no repeated databse connections).

It is quite a large database and every keystroke is sent as an AJAX request, so it ends up with a massive backlog of pending requests. I'd like it to stop/cancel all previous requests (if they haven't been send back) every time it sends a new request.

I've looked at xhr.abort() but I'm pretty sure that will just stop any requests that haven't yet been sent (as opposed to telling the server to stop processing). This is probably OK, but I still don't know how to implement it in my code.

Was it helpful?

Solution

You can use approach similar to this, in order to store the last request in some non-global scope:

function getSendValueFunction(){
    var lastRequest;

    return function(str){
        if (lastRequest){
            lastRequest.abort(); // abort pending request
        }
        // assign pending request, when created
        lastRequest = $.post("ajax.php",{ sendValue: str },
        function(data){
            lastRequest = null; // clear pending request
            $('#display').html(data.returnValue);
        }, "json");

    }
}

var sendValue = getSendValueFunction();

Just remember, that getSendValueFunction returns functions that have separate registers of last pending request. So this will make them have 2 different pending request, completely separated:

var sendValue1 = getSendValueFunction();
var sendValue2 = getSendValueFunction();
sendValue1('aaa');
sendValue2('bbb');
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top