I have this page that consists of a list of user posts / message. When a post is liked, I want it to reflect on all other users, and based on my research setInterval can get the job done by refreshing a specific content for a number of seconds. Currently, I’m having trouble looping through all the user messages and show the updated number of likes. What’s happening is that the number displayed is constantly changing and looping through all the values for a single post. Example: If I have 1, 0, and 2 likes respectively on three different posts, the number for the first post changes to 1, 0, and 2 instead of just showing “1”. I’m kind of a beginner when it comes to AJAX.
Here’s my code:
Jquery / Ajax
function refreshPostLikes() {
setInterval(function() {
$(".posts .id").each(function() { //get id for each post
var postid = $(this).attr("value");
updatePostLikes(postid); //pass the postid variable
});
}, 1000);
}
function updatePostLikes(postid) {
$.ajax({
url: "/main/refresh-post-like.php",
type: "post",
data: {postid: postid}, //send data to php file
success: function(data) {
$(".posts .like").html(data); //output number of likes
}
});
}
PHP Query
<?php
require_once('../connection.php');
$postID = $_POST['postid'];
$likeCountQuery = "select count(*) as total_likes from posts_likes WHERE like_status=1 AND post_id=".$postID; //query number of posts with a like
$likeQueryResult = mysqli_query($conn, $likeCountQuery);
while($likeNumber = mysqli_fetch_assoc($likeQueryResult)) {
$likes = $likeNumber['total_likes'];
if($likes != 0) {
echo $likes;
}
else {
echo '';
}
}
?>
2
Answers
Still not sure this is the best way to go, but the reason your code doesn’t work is due to omitting the postid when updating the HTML in the success part of your code.
with this command
$(".posts .like").html(data); //output number of likes
You are updating all the divs which have these classes specified with the same value.
Set postid as id for the div and change the command to
$("#postid").html(data); //output number of likes
This happens because there is no reference to the post that needs to be updated. What you are doing now is to cycle through all the elements that have the “.posts .id” classes, therefore the update applies to all the posts and not the single one. You should modify your function to make it update only that post (try passing it a unique id in html)
Where N is the id of your post. (For example postid)
Then update the value using this
Prevent SQL Injection
Escape is not enough