0

I have a collapsible element wherein an ajax is requested when the collapsible is opened. However, I also want to stop the ajax request before the collapsible is closed.

$(".collapse").on('show.bs.collapse', function(e) {
    $.ajax
    ({
        type: "GET",
        url: "check_active_operator.php",
        cache: false,
        success: function(r)
        {
            if(r==1){
               //Operator is available

           }else if(r==0){
               //No operator available
           }
        }       
    });
});

$(".collapse").on('hide.bs.collapse', function(e) {
    // STOP AJAX REQUEST
});

NOTE: I also have this ajax request on check_active_operator.php. That request must be aborted as well if the collapsible is closed. As of now, it is still running when the collapsible is closed.

function getMessages(){
    var getchatroomid = $.trim($("#chatroomid").val());
    $.ajax
    ({
        type: "POST",
        url: "messages.php",
        data: {getchatroomid},
        cache: false,
        success: function(data)
        {
        $(".chatMessages").html(data);
        } 
    });
}

setInterval(function(){
    getMessages();
    var c = $('.chatMessages');
    c.scrollTop(c.prop("scrollHeight")); //scroll down
}, 1000); //half a second
D. Gatch
  • 167
  • 4
  • 13
  • Please check this post http://stackoverflow.com/questions/1802936/stop-all-active-ajax-requests-in-jquery – pryxen Feb 09 '17 at 07:26
  • Cache the ``$.ajax`` by declaring the variable outside, defining it inside the ``show`` event, and then aborting it inside the ``hide`` event. – Joshua Feb 09 '17 at 07:27
  • Or this one: http://stackoverflow.com/questions/446594/abort-ajax-requests-using-jquery ... you can just assign the ajax request to a variable and call the `abort()` method on it in the hide.bs.collapse function – Timothy Fisher Feb 09 '17 at 07:27
  • `.abort()` should do the trick. [Read More](http://stackoverflow.com/questions/446594/abort-ajax-requests-using-jquery) – Ankit Feb 09 '17 at 07:28

1 Answers1

0

You can use abort function like this

var xhr;
$(".collapse").on('show.bs.collapse', function(e) {
    xhr = $.ajax
    ({
        type: "GET",
        url: "check_active_operator.php",
        cache: false,
        success: function(r)
        {
            if(r==1){
               //Operator is available

           }else if(r==0){
               //No operator available
           }
        }       
    });
});

$(".collapse").on('hide.bs.collapse', function(e) {
    xhr.abort();
});
bipin patel
  • 2,061
  • 1
  • 13
  • 22