Justin John
Justin John

Reputation: 9616

Avoid previous ajax request on calling the same ajax request again in jquery

I want to avoid previous ajax request on calling the same ajax request again in jquery

<input type="text" id="username" onkeyup = "userName(this)" >



function userName(e) {
    $.ajax({
        type:"POST",
        url:BasePath + "/users/userName",
        data:"name=" + $.trim($(e).val()),
        success:function (resp) {
        if (resp == 1) {
            $('#div.error_message').html('Username already taken...').show();
        } else {
            $('#div.error_message').hide();
        }
        }
    });
}

Upvotes: 2

Views: 1041

Answers (2)

user1432124
user1432124

Reputation:

You can use .abort()

<input type="text" id="username" onkeyup = "userName(this)" >


<script>var xhr=null;
function userName(e) {
     if(xhr)xhr.abort();//first time it will not be aborted
     xhr=$.post(BasePath + "/users/userName",{"name": $.trim($(e).val())},function (resp) {
        if (resp == 1) {
            $('#div.error_message').html('Username already taken...').show();
        } else {
            $('#div.error_message').hide();
        }
        });
}</script>

Use $.post in place of $.ajax as it is simplified and short form of $.ajax

Upvotes: 2

TheVillageIdiot
TheVillageIdiot

Reputation: 40497

var ajaxReq;
function userName(e) {

    if(ajaxReq){
       ajaxReq.abort();
       //OR you may return from here as
       //another request is already in progress
    }

    ajaxReq = $.ajax({
        type:"POST",
        url:BasePath + "/users/userName",
        data:"name=" + $.trim($(e).val()),
        success:function (resp) {
            if (resp == 1) {
               $('#div.error_message').html('Username already taken...').show();
           } else {
               $('#div.error_message').hide();
          }
          ajaxReq=null;
        }
    });
}

Upvotes: 0

Related Questions