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:
<a onclick="javascript:likes(<?php echo $row['Question_ID'];?>);"><button type="submit" class="btn btn-custom btn-sm liketoggle" name ="like"><span>likes: <?php echo $row['likes'];?></span>
<button type="submit" class="btn btn-custom btn-sm liketoggle" name ="like"></button></a>
//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>
AJAX:
function likes(qid) {
if (ajax.readyState == 4 || ajax.readyState == 0) {
ajax.open("POST", 'likes.php?qid='+qid, true);
ajax.onreadystatechange = queried(type);
ajax.send();
}
}
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? How is this possible? The AJAX is doing the job in the database but I want to change the number of likes in the front end.