Idont Reallywolf Idont Reallywolf - 18 days ago 10
Ajax Question

jQuery removeClass and addClass not working

I have created a button and when the user clicks on it, the current class should be replaced with a new one and vice-versa.
BUT addClass or removeClass, are both not showing any effect. I haven't seen any errors or warning msgs in console log.

JQuery code:

$('.vote_btn').click(function(){
$.ajax({
url:'/joseph/pages/votes.php',
type: 'post',
//dataType:'json',
data:{'comment_id':$(this).data('commentid')},
success: function(data){
if(data == 'up'){
$(this).removeClass('fa-thumbs-o-up').addClass('fa-thumbs-up');
} else if(data == 'reversed') {
$(this).removeClass('fa-thumbs-up').addClass('fa-thumbs-o-up');
} else {
alert(data);
}
}
});
});


HTML Code:

<span id="<?=$comment['id']?>" class="fa fa-thumbs-o-up vote_btn" data-commentid="<?=$comment['id']?>" data-postid="<?=$getpost['post_id']?>" data-who="<?=$comment['commenter_id']?>"></span>

Answer

The jQuery object $(this) no longer refers to the clicked .vote_btn. Inside the success callback, store the clicked button in a variable and use this variable inside the callback :

$('.vote_btn').click(function(){
  var _this = $(this);

  $.ajax({
        url:'/joseph/pages/votes.php',
        type: 'post',
        //dataType:'json',
        data:{'comment_id':_this.data('commentid')},
        success: function(data){
          if(data == 'up'){
              _this.removeClass('fa-thumbs-o-up').addClass('fa-thumbs-up');
          } else if(data == 'reversed') {
              _this.removeClass('fa-thumbs-up').addClass('fa-thumbs-o-up');
          } else {
            alert(data);
          }
        }
  });
});

Hope this helps.