Liad Idan Liad Idan - 1 month ago 7
Javascript Question

ajax jquery and click event



I have several buttons that have the same class 'unfollow'.

When the user clicks on one of the buttons it's triggering ajax request and changing the class to 'follow', and adding a click listener to the class.

When the user clicks on the 'follow' button it's triggering a new ajax request and changing the class to 'unfollow'.

Now the result is when the user clicks on the 'unfollow' link everything goes well, but when the user clicks on the 'follow' button it's triggering 2 ajax requests, 1 of the 'unfollow' and 1 of the 'follow'.



Resolved



The new code:

the promises simulate the ajax requests


$('.btn').click(function(event) {
var $self = $(this);
var screenName = $self.parent().prev().children().children('p').text().substring(1);

if ($self.hasClass('unfollow')) {
var unfollowReq = new Promise(function(resolve, reject) {
$self.removeClass('unfollow').addClass('follow');
$self.text('Follow');
console.log('Unfollow');
resolve();
});
} else if ($self.hasClass('follow')){
var unfollowReq = new Promise(function(resolve, reject) {
$self.removeClass('follow').addClass('unfollow');
$self.text('Unfollow');
console.log('Follow');
resolve();
});
}
});


Updated JSFiddle


Regards,

Liad.

Answer

You must remove the follow event listener after the follow click.

Use unbind() for this.

https://api.jquery.com/unbind/