I have a like/unlike button and number of like field and it echos a variable that gets number of likes as follows:
PHP-HTML:
<span>likes: <?php echo $row['likes'];?></span>
<button type="submit" class="btn btn-custom btn-sm liketoggle" name ="like">
//Printing 'Like' if its been liked by user, and 'Unlike' if not liked by user
<? $qid = $row['Question_ID']; $query2 = "SELECT * FROM likes WHERE
user_id='$user_id' and qid = '$qid'";
$results2 = mysqli_query($con,$query2);
if(mysqli_num_rows($results2) == 0){ echo '<span>Like</span>';}
else{echo '<span>Unlike</span>';}?></button>
Javascript - To toggle like/unlike:
$(".liketoggle").click(function () {
$(this).find("span").text(function(i, v){
return v === 'Like' ? 'Unlike' : 'Like'
return v === 'Unlike' ? 'Like' : 'Unlike'
})
});
Is there I way I can increment the number of likes ($row['likes']) when user hits on like, and the same way decrements when unliking?
You can use js to change the number.
<span>likes: <span class="likes-count"><?php echo $row['likes'];?></span></span>
<button type="submit" class="btn btn-custom btn-sm liketoggle" name ="like">
//Printing 'Like' if its been liked by user, and 'Unlike' if not liked by user
<?php $qid = $row['Question_ID']; $query2 = "SELECT * FROM likes WHERE
user_id='$user_id' and qid = '$qid'";
$results2 = mysqli_query($con,$query2);
if(mysqli_num_rows($results2) == 0){ echo '<span>Like</span>';}
else{echo '<span>Unlike</span>';}?></button>
JS:
$(".liketoggle").click(function () {
$(this).find("span").text(function(i, v){
return v === 'Like' ? 'Unlike' : 'Like'
return v === 'Unlike' ? 'Like' : 'Unlike'
});
var likes = $('.likes-count').text();
likes = likes ? parseInt(likes) : 0;
if($(this).find("span").text() == 'Like') likes++;
else if(likes > 0) likes--;
$('.likes-count').text(likes);
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.