Cosmin Ciocan Cosmin Ciocan - 1 year ago 127
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> }

And the Ajax Request:

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

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 Source

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">


$('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']); ?>)">

function doAjax(id) {
   $.ajax(... use "id" here ...);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download