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!

2 Answers 2

0
// put single quotes around JSON string
var images = JSON.parse('<?=$photosArray?>');
1
  • Unfortunately that didn't work, the forward slashes are still all escaped. Commented Mar 14, 2012 at 11:53
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?>];

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.