jQuery Ajax : Like/Unlike

Hi,

I’ve been trying to make my script work, but there is a strange error. When I click “like”, everything works normal, but it doesn’t respond when I click “unlike” after I click “like”. It works if I refresh the page, though. So PHP part has no issue. I think it has something to do with AJAX, but I couldn’t solve it.

PHP part

if ($db->count == 1) {
    // get total number of likes.
    $all_likes = $db->rawQuery("SELECT * from usersxthing_comment WHERE comment_id=?", Array($comment['comment_id']));
    $nok = $db->count;
    ?><a class="removelike" id="removelike<?php echo $comment['comment_id']; ?>" href="">Unlike</a> <?php
    echo $nok . "likes";
} else { ?>
    <a class="like" id="likec<?php echo $comment['comment_id']; ?>" href="">Like</a>
<?php
} ?>

AJAX

$('.like').click(function like(a) {
    a.preventDefault();
    var thisid = $(this).attr('id');
    var thisid1 = thisid.slice(5);
    $.post(
        "/includes/contentpages/process.php",
        {
            likeable: thisid1
        },
        function () {
            $("#likec" + thisid1).html("Unlike");
            // remove class and change id
            $('.like').attr('id', 'removelike' + thisid1);
            $('.like').removeClass('like').addClass('remove-like')

        });
});


$('.removelike').click(function (a) {
    a.preventDefault();
    var thisid2 = $(this).attr('id');
    var thisid3 = thisid2.slice(10);
    $.post(
        "/includes/contentpages/process.php",
        {
            reverselike: thisid3
        },
        function () {
            $("#removelike" + thisid3).html("Like");
            // remove class and change id
            $('.removelike').attr('id','like' +thisid3);
            $('.removelike').removeClass('removelike').addClass('like');
        });
});

You are adding class “remove-like” but binding the click event on “removelike”. Either remove the hyphen or add the hyphen.

It would be helpful if you put $.post() in one method and pass required attributes. This way you can avoid duplicacy of code.

function handleAsynchronousCall( arguments ){
    $.post({
       ...
    })
}

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.