Cosmin Ciocan Cosmin Ciocan - 3 months ago 35
Javascript Question

How to pass php variable from a loop to a javascript variable

I have a while loop which loads the posts of the user and when the like button is clicked to get the post id send it to another php page which will process it and update in the database the likes number but I can't get the good id..
My while loop :

while($posts = mysqli_fetch_array($query)){

<div <?php echo "id=".$posts['id'] ?>
<div class="post">
.
.
</div>
</div> }


And the Ajax Request:

var id = "<?php echo $posts['id'] ?>";
$.ajax({
type: 'POST',
url: 'likes.php',
data: {id:id},
success: function(msg){
alert('Success!');
}
});


But it output only the last value of the while loop and I want for every post to get the id when the like button is pressed.Thanks for help!

Answer

What you're doing would never work. Since you have multiple IDs, you have to retrieve the ID from the <div> that was clicked on, and pass that to your ajax call, e.g.

<div data-id="42" class="clickme">

<script>

$('div.clickme').click(function (e) {
   id = $(this).attr('data-id');
   $.ajax( .... use "id" here ... );
}

alternatively, even something like this would help:

<? while(... fetch from db ... ){ ?>

<div onclick="doAjax(<?php echo json_encode($row['id']); ?>)">

<script>
function doAjax(id) {
   $.ajax(... use "id" here ...);
}
</script>
Comments