tags:

views:

58

answers:

3

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 ?

+6  A: 

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..}
Kevin Peno
A: 

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.

Daniel Vandersluis
A: 

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>";
Zak