Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid overhead of continuous ajax request on keyup event?

e.g. In a search form when user enter some text, at that time, AJAX request should send on each keyup event, with search key as query string. Search key will be value from input box.

If user enters "ABCD", in this case first 3 AJAX request should get kill/cancel, because in 4th AJAX request searchkey will be "ABCD"

$(document).ready(function(){
    $("#searchInput").keyup(function(){
        ajaxSearch( $("#searchInput").val() );
    });
});

On keyup event I am calling following "ajaxSearch()" function.

function ajaxSearch(searchKey) {
    $.ajax({
        type: "get",
        url: "http://example.com/ajaxRequestHandler/",
        data: "action=search&searchkey=" + searchKey
    }).done(function() {
        /* process response */
    });
}
like image 614
Prashant M Bhavsar Avatar asked Dec 03 '14 06:12

Prashant M Bhavsar


1 Answers

var request;
function ajaxSearch(searchKey) {
    /* if request is in-process, kill it */
    if(request) {
        request.abort();
    };

    request = $.ajax({
        type: "get",
        url: "http://example.com/ajaxRequestHandler/",
        data: "action=search&searchkey=" + searchKey
    }).done(function() {
        /* process response */

        /* response received, reset variable */
        request = null;
    });
}
like image 120
Atul Bhosale Avatar answered Oct 11 '22 06:10

Atul Bhosale