Reputation: 5913
My setup is like this (simplified for clarity) :
<div class="methods">
<a href="#a">Method 1</a>
<a href="#b" class="fb_method">FB Method</a>
<a href="#c">Method 3</a>
</div>
... <!-- contents -->
So each method, if clicked, will fade in the inline contents, except anchor that has "fb_method" class, since it needs to do an AJAX request first before appending to its content container in the contents.
So my jQuery is like this :
$('.methods a').click(function(){
// do something global to the anchors, eg : change the bg color, etc
// set the target container
var target = $(this).attr('href');
var xhr;
//if user clicks fb_method buttons
if($(this).hasClass('fb_method')){
//do ajax request - NOTE 1
xhr = $.post("/ajax/get_fb_albums.php",function(msg){
$(target).html('').append(msg).fadeIn();
});
}else{
//abort all ajax request
xhr.abort();
$(target).fadeIn();
}
return false;
});
So what I want is when users first click fb_method button, it will request an AJAX. But if they suddenly change their mind and click other methods, I want to abort the previous AJAX request.
I tracked it via Firebug and it returns an error of the xhr being undefined. if I moved the xhr in NOTE 1 before the if statement, it works but the AJAX request is still being processed. What I mean is in Firebug when I click the FB method then click other methods, it displayed something like this:
// ajax request xhr - keeps on loading
// ajax request xhr aborted
But the request keeps on loading.
Upvotes: 1
Views: 3500
Reputation: 12302
Your xhr variable is local inside the function called when the click event happens.
When you call the abort method, xhr
is not the variable used for the post method.
The xhr variable needs to be external to the function binded to the click event, otherwise it will be undefined when you check it for other click events.
Additionally, since you probably need more than one xhr variable to store different post, you should create an array or an object to store the different post.
var xhr = [];
$('.methods a').click(function(){
// do something global to the anchors, eg : change the bg color, etc
// set the target container
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;
});
Upvotes: 5