Vince
Vince

Reputation: 2646

How to pass php directory files into javascript array?

I am trying to create an image slideshow from a directory on my local server. I'm using php to access the files using readDir(). I them want to pass the variables into a javascript array to then access whatever feature I want with them. Right now I'm just trying to print them out to the screen, to make sure it works, but I'm not getting anything on the screen at all.

<html>
  <head>
  </head>
  <body>
    <script type = "text/javascript">
      var images = new Array();
<?php
$dp = opendir("img/slideshow");
while($currentFile !== false){
  if($currentFile != "." && $currentFile != ".."){
    $currentFile = readDir($dp);
    echo("images.push('{$currentFile}');");
  }
}
?>
      for(var i = 0; i < images.length; i++){
        document.write("<a href = '" + images[i] + "'>" + images[i] + "</a>");
      }
    </script>
  </body>
</html>

It seemed pretty logical to me. I start out with creating the javascript array, then in the php part, I open, and read the directory then echo out a line of code that pushes the current file into the javascript array. Then it should print out each array item, but I'm getting a blank screen. *Note: if I place the files into a php array and print it out, it works just fine but I can't access the array through javascript and put animations to it*

Upvotes: 0

Views: 3627

Answers (2)

user3510753
user3510753

Reputation: 31

<?php
$dir="img/slideshow";//set the working directory
$pics= scandir($dir) ;//Makes a array with all the items of the array
unset($pics[0],$pics[1]);//first and second ellement are the "."".." is nesecery to unset!
$string = '<script type ="text/javascript">var images =[ ';
foreach($pics as $key => $item) {
$string.='"'.$item.'",';
}
echo substr($string, 0, -1)."];</script>"; ?>

Upvotes: 0

idmean
idmean

Reputation: 14875

You can use json_encode(). For example:

<html>
  <head>
  </head>
  <body>
    <script type = "text/javascript">

<?php
$dp = opendir("img/slideshow");
$arrayjs = array();
while($currentFile !== false){
  if($currentFile != "." && $currentFile != ".."){
    $currentFile = readDir($dp);
    $arrayjs[] = $currentFile;
  }
}
echo "var images = " . json_encode($arrayjs) . ";";
?>

      for(var i = 0; i < images.length; i++){
        document.write("<a href = '" + images[i] + "'>" + images[i] + "</a>");
      }
    </script>
  </body>
</html>

Upvotes: 1

Related Questions