Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change button functionality jQuery

I've got 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 content and functionality to button on 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);
        }
    });
});

With this code on page source I see different ID and different text on button but when click second time I call first button like it had never changed. Is there some way to refresh memory for that element or I do wrong thing from start?

like image 315
Stevan Tosic Avatar asked Jul 25 '16 09:07

Stevan Tosic


1 Answers

I think your code should like this

{% 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 current logged in user id, because you can grab it from session :)

Your Ajax Code should be 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');
            }
        }
    });
});

Hope you like my answer and up vote it, mark as correct if it is correct :)

like image 186
Haresh Vidja Avatar answered Sep 21 '22 16:09

Haresh Vidja