johnniexo88
johnniexo88

Reputation: 313

JavaScript does not work inside PHP loop

It seems like when i echo out the result in php, it will loop through the database and display it in the "echo" below but if I try to display it using javascript, it does not even loop. what's the problem in the javascript?

<?php
while($row = $result->fetch()){
    $id = $row['id'];

    echo $id; //loops through and displays the all the id's in order in the database
    ?>

    //this only displays the first id and doesn't loop even though it is in the php while loop
    <script>
        document.getElementById("test").innerHTML = "<?= $id ?>";
    </script>
    <span id="test"></span>

    <?php
}
?>

Upvotes: 1

Views: 2284

Answers (1)

Bhaskar Bhatt
Bhaskar Bhatt

Reputation: 1467

please try with this

<?php

while($row = $result->fetch()){
$id = $row['id'];

echo $id; //loops through and displays the all the id's in order in the database
?>

//this only displays the first id and doesn't loop even though it is in the php while loop

 <!-- change in id name -->
<span id="test_<?=$id?>"></span>

<script type="text/javascript">
   //change here
    document.getElementById("test_<?=$id?>").innerHTML = "<?= $id ?>";
</script>
<?php
    }
  ?>

Upvotes: 3

Related Questions