lakdee
lakdee

Reputation: 55

Using php inside Javascript in a .php

I am trying to display all the files in a folder using PHP.

    var fn=<?php $dir = "folder/*";
    foreach(glob($dir) as $file)  
    {  
    echo $file.'</br>';  
    }
    ?>
    console.log(fn);

The console displays the output as undefined. I am new to using PHP in Javascript, and I am sure I am missing something important here, I appreciate any help.

Upvotes: -1

Views: 52

Answers (1)

David Fontes
David Fontes

Reputation: 1508

@AbraCadaver is right, you are missing quotes when you are assigning the value to the variable fn.

<?php
  $dir = "folder/*";
  foreach(glob($dir) as $file) {  
    $result .= $file . '</br>';
  }
?>

<script>
  var fn = "<?php echo $result; ?>"; // <- Error was here
  console.log(fn);
</script>

Note, that generating JavaScript by joining strings can be tricky and buggy, sometimes better option is passing your data as a JSON object into JS and then working with it with JS:

<?php
$dir = "folder/*";
$arr = [];
foreach (glob($dir) as $file) {
    $arr[] = $file;
}
$jsonObj = json_encode($arr);
?>

...

<script>
    var fn = <?php echo $jsonObj; ?>; // <- in this case DO NOT wrap JSON object with quotes!

    fn.forEach(myFunction);

    function myFunction(item, index) {
        console.log(index, item);
    }
</script>

Upvotes: 3

Related Questions