0

I have a button like this:

<input type="button" id="getresult" value="getresult" />

by clicking on this button one ajax call request active. if i keeps clicking on this button then i get queue of ajax request which are hitting to server and waiting for response. but i want to kill all those request and want to take latest one request.

$('#getresult').click(function() {

var parameters = {data1:'value1',data2:'value2'};

$.post("getresult.php",parameters,function(msg){ 
    console.log(msg);
},'json');

});

I tried the xhr.abort(); by assigning the request to this variable. but whenever i click the button it abort all the request. i am unable to get the latest request. for an eg. if I click on the button 6 times then the 6 request will generate then i want to cancel the prev 5 request and want to proceed the 6th one.

here is the fiddle: http://jsfiddle.net/s4pbn/308/

kosmos
  • 4,253
  • 1
  • 18
  • 36
sumitjainjr
  • 741
  • 1
  • 8
  • 28

1 Answers1

2

Disable the button and reable it once request has completed:

$('#getresult').click(function () {
    this.disabled = true;
    var parameters = {
        data1: 'value1',
        data2: 'value2'
    };

    $.post("getresult.php", parameters, function (msg) {
        console.log(msg);
    }, 'json').always(function () {
        this.disabled = false;
    }.bind(this));
});

EDIT:

I cant disable the button. there is some limitation.

Really not sure why, but then try:

$('#getresult').click(function () {
    if (this.pendingRequest) this.pendingRequest.abort();
    var parameters = {
        data1: 'value1',
        data2: 'value2'
    };

    this.pendingRequest = $.post("getresult.php", parameters, function (msg) {
        console.log(msg);
        this.pendingRequest = null;
    }, 'json');
});

But be aware, that's just stopping client browser to listen for previous request response, not server to handle any previous ones. The first method is better way imho.

A. Wolff
  • 74,033
  • 9
  • 94
  • 155
  • I cant disable the button. there is some limitation. – sumitjainjr Sep 30 '15 at 11:31
  • actually the thing is that I made a button for just to make you understand while in the real scenario i am using a price range slider (if you keeps changing the slider then everytime request is going with new price range) , that was difficult to implement over here. – sumitjainjr Sep 30 '15 at 11:46