useranon
useranon

Reputation: 29514

how to Stop previous ajax call sent in jquery

i am working in rails 2 I have an issue in how to stop previous ajax call on the same element.

For example,

i have categories dropdown which gets updated based on the blog type. And i have clicked type twice , so 2 requests are being sent. Before my second req got over, if i have clicked on the category based on the first response to load sub categories and now the second response to load the categories got over and updated the categories. but the subcategories are the response of one of the category selected from the first response categories.

How to stop the previous ajax call sent to fetch the categories.

Upvotes: 4

Views: 2489

Answers (1)

JNDPNT
JNDPNT

Reputation: 7465

var currentRequest = null;

function someFunction(target){
    currentRequest = jQuery.ajax({
       url: target,

       beforeSend : function()
        {           
            if(currentRequest != null)
            {
                currentRequest.abort()
            }
        },

        success: function() { alert("done"); }
    });
}

Of course the function isn't necessary, just use a variable containing the xhr-object and abort the request before sent.

Upvotes: 4

Related Questions