Monday, July 23, 2012

jQuery One Concurrent Request

Did you ever need to make sure only one request is executed at one time?


For example, a quick search textbox, while you're typing the search phrase, it keeps on asking for answers, but one of them might arrive later than the last key pressed, giving you wrong answers. 


This little snippet keeps track of the urls you requested, it aborts all previous ones and thus giving you only the latest result.

Example usage:

ajaxOneRequest("http://localhost/search", "GET", "jsonp", { "q": $('#searchbox').val() }, function (data)
{ 
    //do something with results
});

<input type="text" id="searchbox" onkeydown="searchclick();"/>

var ajaxOneArray = new Array();
 
function ajaxOneRequest(url, type, dataType, data, onsuccess)
{
    if (ajaxOneArray[url] == null)
        ajaxOneArray[url] = new Array();
             
    ajaxOneArray[url].forEach(function (req)
    {
        req.abort();
    });
             
    ajaxOneArray[url] = new Array();
             
    ajaxOneArray[url].push( 
        $.ajax(
        {
            type: type,
            dataType: dataType,
            url : url,
            data: data,
            success: onsuccess
        })
    );
}

No comments:

Post a Comment