I have two files, slideshow2.html and getimages2.php. The first contains a variable, js_var, with the name of a directory. This will ultimately come from a database. I want to pass js_var to the php file, which creates an array (galleryarray) out of the images in the directory and sends it back to slideshow2 for display.

Here are the relevant bits of slideshow2.html:

<head>
<script src="getimages2.php"></script>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">

//var js_var = "files";
$.ajax({
   type: "POST",
   url: "getimages2.php",
   data: "js_var=files",
   //data: js_var,
   success: function(){
     alert( "success");
   },
    error: function(){
    alert("failure");
  }
 })

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

window.onload=function(){
setInterval("rotateimages()", 2500)
}

</script>
</head>
<body>

<div style="width: 370px; height: 360px">
<img id="slideshow" src="files/alley1.jpg" /> 

</div>

And here's getimages2.php

<?php
$imgDir=$_POST['js_var'];

function returnimages($dirname) {
$pattern="(\.jpg$)|(\.png$)|(\.jpeg$)|(\.gif$)"; //valid image extensions
$pattern1="^[^_]*$"; //filters out files with "_" - i.e. thumbs
$files = array();
$curimage=0;
if($handle = opendir($dirname)) {
while(false !== ($file = readdir($handle))){
if((eregi($pattern, $file)) && (eregi($pattern1, $file))){ 
echo 'galleryarray['.$curimage.']="'.$file .'";';
$curimage++;
}
}
closedir($handle);
}
return($files);
}
echo 'var galleryarray=new Array();'; 
returnimages($imgDir); 
?> 

The Post tab in Firebug says that js_var is being passed to the php file, and the Response tab shows the array of images, but they are not displayed. If I change the ajax data input from "js_var=files" to "js_var" (with variable declared above) the Response tab does not show the array.

I think I'm missing something pretty basic here. Can anyone point me in the right direction?

I thought the data in the $.ajax function should be passed as an object. E.g.

$.ajax({
    url: 'getimages2.php',
    type: 'post',
    data: {
        'js_var': 'value'
    },
    // ...
});

Thanks for the suggestion. Tried that format, but unfortunately the image array is still not being passed back to the html file. The DOM tab shows galleryarray as empty.

Doh! I had forgotten to include the Header("content-type: application/x-javascript"); tag in the php file. Everything hunky dory now!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.