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
  • 1
    Check this Abort Ajax requests using jQuery Commented Jul 28, 2012 at 11:59
  • Do you want to stop the ajax request or the fadeIn-animation? Commented Jul 28, 2012 at 14:52

2 Answers 2

3

Set a variable for your AJAX request.

var getajax;

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

     ......
    });
}

When you want to abort it, simply

getajax.abort();
Sign up to request clarification or add additional context in comments.

Comments

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;
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.