0

I am using backstretch to create a fullscreen background slideshow using the images defined in a wordpress page.

I have written a function that can output the src of each image to an array. However, I am encountering issues passing this php array into the javascript, or perhaps the way the string is parsed in javascript due to slashes etc.

Backstretch requires an array of images like so:

var images = [
      "http://dl.dropbox.com/u/515046/www/outside.jpg"
    , "http://dl.dropbox.com/u/515046/www/garfield-interior.jpg"
    , "http://dl.dropbox.com/u/515046/www/cheers.jpg"
  ];

Currently, I am trying to urlencode and then json_encode, but it doesn't seem to work:

$photos = get_post_images();
$photosArray = array();

foreach ($photos as $photo) {
    $photosArray[] = $photo[0];
}

$photosArray = json_encode($photosArray);

where $photo[0] is the url to an image like:

http://server/directory/file.jpg

Then in the Javascript:

var images = JSON.parse(<?=$photosArray?>);

As recommended by this stackoverflow question which gives an error:

Uncaught SyntaxError: Unexpected token h

Then I try simply passing the array but it is always escaping the slashes:

http:\/\/server\/wp\/

Can anyone recommend a solution?

Thank you!

Community
  • 1
  • 1
waffl
  • 5,179
  • 10
  • 73
  • 123

2 Answers2

0
// put single quotes around JSON string
var images = JSON.parse('<?=$photosArray?>');
Ruslanas Balčiūnas
  • 7,310
  • 3
  • 24
  • 41
0

I ended up building the variable as a string in PHP then echoing it in the javascript. Not what I would consider the most ideal solution, but as there seemed to be no other solution:

$counter = 0;    
foreach ($photos as $photo) {
    $photos_js .= "\"".$photo[0]."\"";
    $counter++;

    if ($counter < count($photos)) {
    $photos_js .= ",";
    }
}

Then in Javascript:

var images = [<?=$photos_js?>];
waffl
  • 5,179
  • 10
  • 73
  • 123