Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript: How to abort $.post()

I have the post method as shown below:

$(".buttons").click(function(){
  var gettopic=$.post("topic.php", {id: topicId}, function(result){
  // codes for handling returned result

  });
})

I tried to abort the old post when a new button is clicked: So I tired

$(".buttons").click(function(){
    if (gettopic) {
        gettopic.abort();
    }
    var gettopic=$.post("topic.php", {id: topicId}, function(result){
         // codes for handling returned result
    });
})

However this is not working. So I wondered how this could be fixed?

like image 950
badbye Avatar asked Aug 16 '16 06:08

badbye


2 Answers

You have to define your variable gettopic outside the click event

var gettopic;
$(".buttons").click(function(){
    if (gettopic)
    {
    gettopic.abort();
    }
    gettopic=$.post("topic.php", {id: topicId}, function(result){
               // codes for handling returned result
    });
})
like image 197
Amani Ben Azzouz Avatar answered Sep 29 '22 16:09

Amani Ben Azzouz


var xhr = [];

$('.methods a').click(function(){
    var target = $(this).attr('href');

    //if user clicks fb_method buttons
    if($(this).hasClass('fb_method')){
        //do ajax request (add the post handle to the xhr array)
        xhr.push( $.post("/ajax/get_fb_albums.php", function(msg) {                           
            $(target).html('').append(msg).fadeIn();
        }) );
    } else {
        //abort ALL ajax request
        for ( var x = 0; x < xhr.length; x++ )
        {
            xhr[x].abort();
        }
        $(target).fadeIn();
    }
    return false;
});

Using jquery you can use in this way:

var xhr = $.ajax({
    type: "POST",
    url: "some.php",
    data: "name=John&location=Boston",
    success: function(msg){
        alert( "Data Saved: " + msg );
    }
});

//kill the request
xhr.abort()
like image 42
satwick Avatar answered Sep 29 '22 17:09

satwick