I am trying to make a follow/unfollow button. The follow button works fine. On click I change the button id to "unfollow" but when I click the button again (when it has the id "unffollow") it acts as if it still has the id of "follow" which means it's still using the first ajax method as so:
$("#fbtn").on('click',function(){
var fbtn = $('#fbtn');
var followee_name = $('#author').text();
$.ajax({
url: '/follow',
method: 'POST',
//dataType: 'application/json',
data:{followee_name:followee_name},
success: function(response){
console.log("Followed")
fbtn.text('Unfollow');
fbtn.attr('id','unfollow');
}
});
});
Then:
$("#unfollow").on('click',function(){
var unfollowbtn = $('#unfollow');
$.ajax({
url: '/unfollow',
method: 'DELETE',
//dataType: 'application/json',
success: function(response,err){
if(err){
console.log(err);
}
console.log("Unfollowd")
unfollowbtn.text('Follow');
unfollowbtn.attr('id','fbtn');
}
});
});
HTML:
<a id="author" href="#"><%= showPost.username %></a> //this displays a username
<button style="width:100px;" type="button" id="fbtn">Follow</button>
I don't know where I went wrong, in theory this looks fine to me but I am new to jquery and ajax and I must have missed something.