Reputation: 81
I have this script. It works great if the topic is already liked, but if it has never been marked liked, you need to double click for it to show the user has liked. How do I get it to work the first time. Its a continuation from old conversation I had gotten some great help from on here old conversation
$(document).ready(function(){
$("#like<? echo $msgID;?>").click(function(){
var isLike = $(this).text() === "Like",
url = isLike ? "status-updates/like.php?status_id=<? echo $msgID;?>&user=<? echo $session->username;?>" : "status-updates/unlike.php?status_id=<? echo $msgID;?>&user=<? echo $session->username;?>";
$.post(url + "?status_id=<? echo $msgID;?>&user=<? echo $session->username;?>", $(this).serialize());
setTimeout(function () {
$("#likeDiv<? echo $msgID;?>").load('status-updates/like-count.php?status_id=<? echo $msgID;?>');
$(".whoLikes<? echo $msgID;?>").load('status-updates/who-likes.php?status_id=<? echo $msgID;?>');
$("#like<? echo $msgID;?>").text(isLike ? "Unlike" : "Like");
}, 500);
});
});
Upvotes: 0
Views: 47
Reputation: 7401
I suspect that your problem may come down to these lines:
var isLike = $(this).text() === "Like";
url = isLike ? "status-updates/like.php?status_id=<? echo $msgID;?>&user=<? echo $session->username;?>" : "status-updates/unlike.php?status_id=<? echo $msgID;?>&user=<? echo $session->username;?>";
or, in a non-very-long-scrolling-way,
var isLike = $(this).text() === "Like";
url = isLike ? <like URL> : <unlike URL>;
In other words, when the text already says "Like", the URL being POST
ed to is the one that actually does the "like".
Incidentally, there is a neater way to perform the delay you're invoking with your setTimeout
, which seems designed to wait half a second - sufficient, you're hoping, for the post
to complete - before running. Instead, you can simply run the code once the POST has completed by using the third parameter of $.post
:
$.post( <url>, <data>,
function () {
$("#likeDiv<? echo $msgID;?>").load('status-updates/like-count.php?status_id=<? echo $msgID;?>');
$(".whoLikes<? echo $msgID;?>").load('status-updates/who-likes.php?status_id=<? echo $msgID;?>');
$("#like<? echo $msgID;?>").text(isLike ? "Unlike" : "Like");
}
);
Upvotes: 1