0

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. :)

  • Also I think in your success event it should to be `var likes = data.likes` It is a JSON object not array. – SaidbakR Oct 20 '17 at 21:36
  • 1
    @SaidbakR `data['likes']` is synonymous with `data.likes` – Nathan Hinchey Oct 20 '17 at 21:40
  • Can you share the upvote.php code? I'm just curious - because it seems like it's related to ID mismatches or not being generated properly, since you're not replacing the object(s) you attached the click listener to to start with (so attaching the listener to a parent wouldn't really affect it). One thing I want to see is the use of `postid` as the variable name from your AJAX, but your other PHP shows `id_post` instead. It's also hard to tell if your quotes are properly setup since you show the HTML that PHP prints out, but also left some PHP in there... –  Oct 20 '17 at 21:46
  • @mark.hch edited the question with php code – Ruben Perdigao Oct 20 '17 at 21:54
  • Sorry, I guess I was just confused for a moment, that PHP doesn't really affect the answer, it would be the PHP that creates the new `.upvote-vetor` elements. Instead of posting it, though, if you check your Dev Tools and look at the dynamically loaded `.upvote-vetor` elements, do they look identical to the pre-loaded ones (at least identical except for the ID and text content)? If so, then the code you mentioned (and is in the duplicate question post, and @NathanHinchey answered with) should work as long as the format is `$(document).on('click', '.upvote-vetor .like', function() { });` –  Oct 20 '17 at 22:05

1 Answers1

1

You need to attach a listener to a parent element that already exists, to listen for clicks on the relevant element. For example:

$('body').on('click','.upvote-vetor .like', my_function)
Nathan Hinchey
  • 1,191
  • 9
  • 30