Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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*

share|improve this question
3  
You have a stray < at the start of your echo that would cause a JS parse error. When you execute this do you get any errors from PHP or in the JS console? – Adrian Mar 14 at 17:23
You seem to have an extra < in the following line echo("<images.push('{$currentFile}');");.. You need to remove that. – Steve Mar 14 at 17:23
I apologize, that's not in my actual code, I misprinted it when typing it here. Sorry. – Vince Mar 14 at 17:24

1 Answer

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>
share|improve this answer
Do I need a special library for json_encode? – Vince Mar 14 at 18:25
No, json_encode is in intergrated in php . – wumm Mar 14 at 18:51

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.