Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

zoldic's avatar

AJAX update like and unlike

Hi folks, I have this like and unlike system in my web app

I have managed to make all the back-end work well (creating, deleting the like), but I still have problem with updating my like/unlike button and its count without refreshing my page using AJAX (it has no problem if I refresh it, everthing will load correctly)

my view

<button type="button" data-like="{{ $reply->id }}">
    {{ $reply->isLikedByAuthUser($reply->likes) ? 'unlike' : 'like' }
    <span>{{ $reply->likes->count() }}</span>
</button>

my js

$('[data-like]').on('click', function(e) {
        var self = $(this),
            replyId = self.data('like');

        self.prop('disabled', true);

        $.ajax({
            type: "POST",
            url: urlLike,
            data: {replyId: replyId},
        }).done(function() {
            //what should I add here?
        }).always(function() {
            self.prop('disabled', false);
        });
    });

I want to update my like button without page refresh just like facebook like

if a thread already has 10 likes,

and a user click the like button, it will be 11 likes, so the button will print like this ( unlike (11) ),

if the user change his mind and want to unlike the thread, and he click the button so it will be back to ( like (10) )

What should I add to my AJAX's .done(function() {}

0 likes
3 replies
cre3z's avatar

Can you not send back the count of likes/dislikes as a response to your request?

Else you can just get the value of your count in JavaScript (maybe get the value of the container) and decrease/increase it's value based on what the user clicked.

1 like
RamjithAp's avatar
Level 10

Update your code like below

<button type="button" id="btn" data-like="{{ $reply->id }}">
    {{ $reply->isLikedByAuthUser($reply->likes) ? 'unlike' : 'like' }
    <span id="count">{{ $reply->likes->count() }}</span>
</button>

$('[data-like]').on('click', function(e) {
        var self = $(this),
        replyId = self.data('like');
        self.prop('disabled', true);

        $.ajax({
            type: "POST",
            url: urlLike,
            data: {replyId: replyId},
        }).done(function(data) {
            $('#count').html(data.current_count);
            if ($("#btn").html() == "like") {
            $("#btn").html('unlike');
            }
           else {
           $("#btn").html('like');
           }
        }).always(function() {
            self.prop('disabled', false);
        });
    });

And then your /urllike controller should send response like below

return "{'current_count':21}";
2 likes
cre3z's avatar

Just like @RamjithAp suggests. Send the count back and update the container count via JavaScript!

1 like

Please or to participate in this conversation.