Reputation: 171
I have created a like button for my page using jquery, html and php. And now I'm trying to read out the total amount of likes.
When I click on the it goes through my jquery and php and returns the total amount in my console. But I can't see it on the page until I update the page.
PHP and HTML
<?php
$page = new CMS();
$gp = $page->getPage();
foreach ($gp as $sp) {
//var_dump($sp);
echo "<div class='pub'>";
echo "<h4 class='pub-headline'>" . $sp['title'] . "</h4>";
echo "<article class='pub_art'>" . $sp['content'] . "</article>";
echo "<p class='pub_created'>" . $sp['created'] . "</p>";
echo "<p class='pub_created_by'>". $sp['writer'] ."</p>";
echo "<button class='show'>Show</button>";
echo "<button class='noshow'>Hide</button>";
echo "<div class='vote_widget'>";
echo "<div class='voting' onclick='vote(" . $sp['id'] . ", 1)'></div>";
echo"<div class='total_likes'>" . $sp['likes'] . "</div>";
echo"</div>";
echo "</div>";
}
?>
Jquery
function vote(id, likes) {
$.post("classCalling4.php",
{ id: id, likes: likes }, function(result){
console.log(result)
$(".total_likes" + id) .html(result);
;
});
OOP PHP
public function updateLikes($id, $likes) {
$id = mysqli_real_escape_string($this->db, $id);
$likes = mysqli_real_escape_string($this->db, $likes);
$id = intval($id);
$likes = intval($likes);
$sql = "UPDATE pages
SET likes = likes+1
WHERE id = $id ";
$result = mysqli_query($this->db, $sql) or die("Fel vid SQL query 1"); // Hit kommer jag
$sql2 = "SELECT * from pages WHERE id = $id ";
$result2 = mysqli_query($this->db, $sql2) or die ("Fel vid SQL query 2");
$row = mysqli_fetch_array($result2);
$tot_likes = $row['likes'];
echo $tot_likes;
}
Upvotes: 0
Views: 60
Reputation: 7023
you should add the id to class name because you suppose this in your jquery script:
$(".total_likes" + id) .html(result);
so your html should be:
echo"<div class='total_likes".$sp['id']."'>" . $sp['likes'] . "</div>";
and if you use this class to give style you can replace the class with id:
echo"<div class='total_likes' class='total_likes".$sp['id']."'>".$sp['likes']."</div>";
and your javascript should be:
$("#total_likes" + id) .html(result);
Upvotes: 1
Reputation: 7987
Since, the total_likes
is in foreach
loop so you should concate id
with the class name to make it unique.
So, instead of
echo"<div class='total_likes'>" . $sp['likes'] . "</div>";
do this
echo"<div class='total_likes'".$sp['id'].">" . $sp['likes'] . "</div>";
Upvotes: 1