Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

storing a php array in a javascript array

This is my php code that gets a list of files in a dir and stores it in the array $files: (Note I tried running this in a fiddle here but not sure if I am able with this example)

<?php

echo "<hr>";
echo "<hr>";


$files = array_slice(scandir('/path/to/dir'), 2); // this gets a list of all files in the dir

//
echo "this is the array: <br>";
print_r($files); // this prints the array 
echo "<br>";
echo "<br>";

echo "this is each element in the array: <br>";
foreach ($files as &$value) {
    print_r($value."<br>"); // this prints each element of the array 
}

echo "<hr>";
echo "<hr>";
?>

Immediately after that is my javascript where I want to store the php array in my javascript variable, but I get this error Uncaught SyntaxError: Unexpected token ILLEGAL in the console. Can anyone correnct the erro in my ways?

<script>
// then echo it into the js/html stream
// and assign to a js variable
var jsfiles =[];
jsfiles = "<?php print_r($files);?>";

// then
alert(jsfiles);
console.log("the files are:",jsfiles);

</script>

EDIT2 tried jsfiles = "<?php json_encode($files);?>"; which gives me no error but values in array are not displayed in console.log("the files are:",jsfiles);


EDIT3 - got it working

snippet of my code. I had to delete the 2 lines below, even though I though they were commented out. Not sure why

<script>
// then echo it into the js/html stream
// and assign to a js variable
//var jsfiles =[];
//jsfiles = "<?php print_r($files);?>";   ------ had to delete this line
//jsfiles = <?php json_encode($files) ?>; ------ had to delete this line
var jsfiles = <?php echo json_encode($files) ?>;
like image 268
HattrickNZ Avatar asked Sep 18 '25 21:09

HattrickNZ


1 Answers

Always always always use json_encode when outputting PHP to javascript.

var jsfiles = <?php echo json_encode($files) ?>;

Even if this were just a number or simple string, json_encode protects you from surprises and ensures it will be valid javascript object notation.

like image 99
jszobody Avatar answered Sep 20 '25 12:09

jszobody