JQuery change button function

I have this code in twig

{% if followsId == null %} <div id="followUser" class="follow" data-userId="{{ profileUserData.id }}" data-currentUserId="{{ loggedUserData.id }}" data-action="follow"> Follow </div> {% else %} <div id="unFollowUser" class="follow" data-followsId="{{ followsId }}"> Unfollow </div> {% endif %} 

I just wanted to change the content and functionality of the button on a click and tried this code with jQuery

 $('#followUser').click(function () { var userId = $(this).attr('data-userId'), action = $(this).attr('data-action'), currentUser = $(this).attr('data-currentUserId'); $.ajax({ method: 'POST', url: "/sci-profile/profile/follow", data: { userId: currentUser, profileUserId: userId, action: action }, success: function(response) { $('#followUser').attr('id', 'unFollowUser') .text('Unfollow') .fadeOut(50) .delay(50) .fadeIn(50); } }); }); 

Using this code on the source page, I see different identifiers and different texts on the button, but when I click the second time, I call the first button, as if it never changed. Is there a way to update the memory for this item, or am I doing the wrong thing from the start?

+5
source share
1 answer

I think your code should like

 {% if followsId == null %} <div data-action="follow" class="follow" data-user-id="{{ profileUserData.id }}"> Follow </div> {% else %} <div data-action="unfollow" class="follow" data-user-id="{{ followsId }}"> Unfollow </div> {% endif %} 

No need to store the current registered user ID, because you can grab it from the session :)

Your Ajax code should look like this

 $('.follow').click(function () { var _this= $(this); var userId = $(this).data('user-id'); var action =$(this).data('action'); $.ajax({ method: 'POST', url: "/sci-profile/profile/follow", data: { profileUserId: userId, action: action }, success: function(response) { if(action=="follow") { _this.attr('data-action', 'unfollow').text('Unfollow'); } else { _this.attr('data-action', 'follow').text('Follow'); } } }); }); 

I hope you enjoy my answer and vote for it, mark as correct if this is correct :)

+4
source

All Articles