jquery - How to put values back from php data to ajax success

I'm not even sure if my title is right. Anyway, I'm creating a page where users can submit messages / post and currently trying to figure out how to update the number of likes per post for a particular number of seconds using short-polling (i.e. setinterval) -- this is intentional for now. This is only a practice and I know I'm not using parameterized queries and short polling isn't ideal, but I'll park that for now. This may be my longest post, sorry but I was told this is way much more convenient than providing half baked inputs / questions.
I have this Jquery:
function refreshPostLikes() {
var postid_array = []; //establish array for postid
$(".post .postid").each(function () {
//get id for each post
var postid = $(this).attr("value");
postid_array.push(postid); //place all the postid in an array
});
updatePostLikes(postid_array); //pass the array
}
function updatePostLikes(postid) {
setInterval(function () {
$.ajax({
url: "/main/refresh-like.php",
type: "post",
data: { postid: postid }, //send postid array to php file
success: function (data) {
alert(data); //testing because I don't know how
},
});
}, 20000); //just 20 seconds interval
}
refreshPostLikes(); //run function
Here's my PHP file, refresh-like.php!
<?php
require_once '../connection.php';
$postID = trim(json_encode($_POST['postid']), '[]'); //convert array to string and remove square brackets to be a valid value for MySQL query
$likeQuery = "select count(*) as total_likes from likes where post_id in ('.$postID.') group by post_id order by post_id desc"; //query number of likes
$likeResult = mysqli_query($conn, $likeQuery);
while ($row = mysqli_fetch_assoc($likeResult)) { //loop through the query
$likes = $row['total_likes'];
echo $likes; //output number of likes per post and pass it to ajax data success
}
?>
Using the codes above, if I have three posts (with a mix of 1, 2, and 0 likes), the alert under Ajax success as I noted "testing because I don't know how" will show a message: 1, 2, 0, which is correct! The numbers are together in a single alert, fyi.
Now my question is how can I pass those values back to each post under likes div? What I mean is 1 like is for postid1, 2 likes for postid2, and 0 likes for postid3. Usually I select a single element and pass using .html, but how to do it if the php data returned is altogether (i.e. 2, 1, 0). I know I need to make adjustments here:
success: function(data) {
alert(data); //testing because I don't know how
}
Say I have this HTML:
<div class="post">
<div class="postid">1</div>
<div class="message">blah blah</div>
<div class="likes">1</div> //pass the value back here
</div>
<div class="post">
<div class="postid">2</div>
<div class="message">blah blah</div>
<div class="likes">2</div> //pass the value back here
</div>
<div class="post_3">
<div class="postid">3</div>
<div class="message">blah blah</div>
<div class="likes">0</div> //pass the value back here
</div>
Answer
Solution:
First you need to have some sort of table to match what post has what likes. Then you can update the content of the{-code-{-code-3}}
div of corresponsing post.
Quick and dirty
Since your PHP is already returing the string{-code-2}
for posts{-code-3}
,2
and3
, the minial effort would be to simply split that string in Javascript and then updated the{-code-{-code-3}}
div in order:
success: function(data) {
var likes = data.split(", "); // likes will hold ["{-code-3}", "2", "0"]
$('{-code-{-code-3}}').each(function(i, likeDiv) {
$(likeDiv).text(likes[i]);
});
}
This will work in your particular case but is relying on the fact that your HTML is ordered in the exact same way that your posts are in the database. So not very resilient.
Instead I'd suggest you change your PHP to have both likes count and post id and echo the whole as JSON
JSON
PHP
<?php
require_once '../connection.php';
$postID = trim(json_encode($_POST['postid']), '[]'); //convert array to string and remove square brackets to be a valid value for MySQL query
$likeQuery = "select count(*) as total_likes from likes where post_id in ('.$postID.') group by post_id order by post_id desc"; //query number of likes
$likeResult = mysqli_query($conn, $likeQuery);
// build output collection
$output = [];
while ($row = mysqli_fetch_assoc($likeResult)) { //loop through the query
$output[] = [
'post_id' => $row['post_id'],
'likes' => $row['total_likes']
];
}
echo json_encode($output);
// [{"post_id": {-code-3}, "likes": {-code-3}}, {"post_id": 2, "likes": 2}, {"post_id": 3, "likes": 0}]'
?>
JS
success: function(data) {
var postsLikes = JSON.parse(data);
for (var i = 0; i < postsLikes.length; i++) {
// find corresponding post
var $post = $('.postid').filter(function(j, postIdDiv) {
return postIdDiv.textContent == postsLikes[i].post_id
}).parent()
// update likes count in post
$post.find('{-code-{-code-3}}').text(postsLikes[i]{-code-{-code-3}})
}
}
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: can't write image data to path
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.