johnniexo88 johnniexo88 - 5 months ago 10
HTML Question

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
}
?>

Answer

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
    }
  ?>
Comments