View Full Version : Need help with "Dynamically populating a JavaScript image slideshow"

08-20-2011, 03:15 PM
Hi, I'm completely new to web design & php so I'm trying to follow the tutorial here (http://www.javascriptkit.com/javatutors/externalphp2.shtml) which uses php to return a list of images in a folder then display them.
However when I try implementing this on my machine (so putting the php code into one file, the javascript into a main html with some jpegs in the same folder) but I get the following errors:

getimages.php:1 Uncaught SyntaxError: Unexpected token <
getimages.php:-1 Resource interpreted as Script but transferred with MIME type text/php
The php file is as follows:

//PHP SCRIPT: getimages.php
Header("content-type: application/x-javascript");

//This function gets the file names of all images in the current directory
//and ouputs them as a JavaScript array
function returnimages($dirname=".") {
$pattern="(\.jpg$)|(\.png$)|(\.jpeg$)|(\.gif$)"; //valid image extensions
$files = array();
if($handle = opendir($dirname)) {
while(false !== ($file = readdir($handle))){
if(eregi($pattern, $file)){ //if this file is a valid image
//Output it as a JavaScript array element
echo 'galleryarray['.$curimage.']="'.$file .'";';


echo 'var galleryarray=new Array();'; //Define array in JavaScript
returnimages() //Output the array elements containing the image file names

Any help would be much appreciated!

08-20-2011, 07:47 PM
The code works fine. Are you including this in another file?

08-22-2011, 12:15 AM
I have this in an html file in the same directory:

<script src="getimages.php"></script>

<script type="text/javascript">

var curimg=0
function rotateimages(){
document.getElementById("slideshow").setAttribute("src", galleryarray[curimg])
curimg=(curimg<galleryarray.length-1)? curimg+1 : 0

setInterval("rotateimages()", 2500)

<div style="width: 170px; height: 160px">
<img id="slideshow" src="1.jpg" />

Which is taken from the tutorial website, but with the file path's changed slightly to fit what I have