i have a upvote posts style layout on my website, i have an ajax request that loads more posts, that code works fine, but my problem is when i try to upvote them. The ones that are not dynamically showed from the ajax request can be upvoted but when it loads more they can't be upvoted.
I have a id like_postID
so the code can check wich post is being upvoted.
Searching i came across the $(document).on( eventName, selector, function(){} );
, i tried it and it still works but only the ones that are not requested by the ajax call.
Heres my HTML code:
<div class="contain">
<div class="upvote-vetor">
<a href="javascript:void(0)"><img alt="" src="images/upvotes.png" id="like_'.$post['id_post'].'" class="like"></a>
<p id="likes_'.$post['id_post'].'">'.$upvote['upvotes'].' Up Votes</p>
</div>
Heres i my Jquery:
$(document).ready(function(){
// like and unlike click
$(".upvote-vetor").on("click",".like", function(){
var id = this.id; // Getting Button id
var split_id = id.split("_");
var text = split_id[0];
var postid = split_id[1]; // postid
// Finding click type
var type = 1;
// AJAX Request
$.ajax({
url: 'php/upvote.php',
type: 'post',
data: {postid:postid,type:type},
dataType: 'json',
success: function(data){
var likes = data['likes'];
$("#likes_"+postid).text(likes); // setting likes
},
error: function(data){
alert("error : " + JSON.stringify(data));
}
});
});
});
PHP upvote code:
$userid = $id_user;
$postid = $_POST['postid'];
// Check entry within table
$query = "SELECT COUNT(*) AS upvotes FROM upvotes WHERE id_post='$postid' and id_user= '$userid'";
$result = $conn->prepare($query);
$result->execute();
$fetchdata = $result->fetch(PDO::FETCH_ASSOC);
$count = $fetchdata['upvotes'];
if($count == 0){
$insertquery = $conn->prepare("INSERT INTO `upvotes` (`id_upvote`, `id_user`, `id_post`) VALUES (NULL, '$id_user', '$postid');");
$insertquery ->execute();
}else {
$updatequery = $conn->prepare("DELETE FROM `upvotes` WHERE id_user= '$userid' and id_post='$postid'");
$updatequery->execute();
}
// count numbers of like and unlike in post
$query2 = "SELECT COUNT(*) AS upvotes FROM upvotes WHERE id_post='$postid'";
$result2 = $conn->prepare($query2);
$result2->execute();
$fetchlikes = $result2->fetch(PDO::FETCH_ASSOC);
$totalLikes = $fetchlikes['upvotes']. " Up Votes";
$return_arr = array("likes"=>$totalLikes);
echo json_encode($return_arr);
Thanks in advance. :)