0

I have a jquery function like this:

function get()
 {
$.ajax({
     url: 'get.php',
     success: function(data) {
     $('#get').html(data);
     $('#get').fadeIn(2000);
     setTimeout(posts,2000);
    }
    });
 }
 get();

I want to stop this function when i click on a certain element in a webpage, how would i do this.

Thanks

2 Answers2

3

Set a variable for your AJAX request.

var getajax;

function get() {
    getajax = $.ajax({

     ......
    });
}

When you want to abort it, simply

getajax.abort();
uzyn
  • 6,625
  • 5
  • 22
  • 41
0

In a situation where you may not be able to globaly define all of your .ajax() call variables (as shown by another answer by @uzyn), this might be a suitable solution.

You could simply wrap your success callback with a flag indicating whether you want to cancel the result.

var ajax_canceled = false;

function get(){
  $.ajax({
    url: 'get.php',
    success: function(data) {
      if (!ajax_canceled){
          //...
      }
    }
  });
}
get();

$("#cancel_ajax").on('click',function(){
  ajax_canceled = true;
});
Community
  • 1
  • 1
Lix
  • 47,311
  • 12
  • 103
  • 131