1

I like to get a dir listing in php

glob("*.jpg"); 

or

$dir = '.'; //requested directory to read $notthat = array('.', '..'); //what not to include $listedfiles = array_diff(scandir($dir), $notthat); // removed what not to include 

so i like to send that array to a javascript like that (slides = $listedfiles)

function startSlideshow(slides) { .. do something..} 

What is the best way to do that ?

3 Answers 3

6

json_encode is your friend for this. No looping is necessary. It will return a pure json object string that you can then just echo into your js file using PHP. Example:

var slides = <?php echo json_encode( $filelistarray );?> function startSlideshow(slides) { .. do something..} 
Sign up to request clarification or add additional context in comments.

Comments

0

you can always just do an echo of it to a javascript :

echo ' <script type="text/javascript"> var filelist = []; '; foreach($listedfiles as $file) { echo " filelist[] = $file; "; } echo "</script>"; 

Comments

0

PHP and Javascript cannot directly interact, however, you can output Javascript from PHP the same way you can output plain text or HTML:

<script type="text/javascript"> var slides = []; <?php foreach ($listedfiles as $file) { echo "slides[] = '" . addslashes($file) . "';\n"; } ?> // ... do js stuff </script> 

Basically, after creating your array in PHP, you output the JS code to create the same array in javascript.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.