N Kumar
N Kumar

Reputation: 1312

Restart or override Ajax request

I have two functions autosubmit() and manualsubmit()

function autosubmit() {
    $.post('action.php', $('#form').serialize(), function(data){
        $('#container').html(data);
    });
}

function manualsubmit() {
    autosubmit();
}

autosubmit() is called on body load but sometime it takes time to load data in container then manualsubmit() is triggered by clicking try again button. I want to abort previous ajax request sent to server. I am unable to implement abort() method.

Upvotes: 0

Views: 545

Answers (3)

Rory McCrossan
Rory McCrossan

Reputation: 337590

The use of $.post does not preclude the use of abort. It returns a jqXHR object the same as $.ajax so you can call its abort method, something like this:

var previousRequest;

function autosubmit() {
    previousRequest = $.post('action.php', $('#form').serialize(), function(data){
        $('#container').html(data);
    });
}

function manualsubmit() {
    previousRequest && previousRequest.abort(); // abort the request, if there was one
    autosubmit();
}

Note that this does not stop the AJAX request being made (as that is not possible), only the return handler for that request being executed.

Upvotes: 1

Mooseman
Mooseman

Reputation: 18891

You can't cancel an ajax request once it's sent. You can only ignore the returned value in JS.

You can use .data to cancel showing the returned value:

function autosubmit(){
  $body = $("body");
  if($body.data('autosubmit') !== true){
    $.post('action.php', $('#form').serialize(), function(data){
      if($body.data('autosubmit') !== true) $('#container').html(data);
    });
  }
}

function manualsubmit(){
  $("body").data('autosubmit',true);
  $.post('action.php', $('#form').serialize(), function(data){
    $('#container').html(data);
  });
}

Explanation: Once manualsubmit() is called, it adds 'autosubmit' => true to the body of the document with jQuery's .data. If autosubmit() is called, or if its ajax request is returned, it makes sure the aforementioned value is absent before requesting or presenting the data.

Upvotes: 2

jogesh_pi
jogesh_pi

Reputation: 9782

Take a look on this example:

var currentRequest = null;
currentRequest = $.ajax({
    url: 'action.php', 
    type: 'post', 
    data: {your_fields_params},  
    beforeSend: function(){
        if( currentRequest != null )
            currentRequest.abort();
    }, 
    success: function(){
    }
});

Upvotes: 1

Related Questions