Jump to content

JSON and PHP for a slideshow


thescientist

Recommended Posts

Hey everyone. I'm working on personal website project of mine and I was hoping if I could get some help/and or insight to the last big hurdle for completing my site. I am using PHP to scan a directory and return to me all the file paths of images in it. This works fine and I can use the array I save all the image paths in to print out in a loop and use one of the image paths to set the src of an img. All of this works in PHP.PHP

<?php...//getting a folder, then scanning it$directory = $row['picturesDirectory'];$pictures = scandir($directory);...$paths = Array();$k = 0;$findme = '.jpg';$l = count($pictures);for($i = 0; $i < $l; $i++){  $string = $pictures[$i];  $jpos = stripos($string, $findme, 0);  if($jpos !== false){	$paths[$k] = ($directory . "/" . $pictures[$i]);	$k++;  };};//verify the paths came out rightecho "paths count: " . count($paths) . " k: " . $k . "<br/>";for($v = 0; $v < $k; $v++){  echo $paths[$v] . "<br/>";};echo "paths: " . $paths ."<br/>";echo "<img src='" . $paths[0] . "'/>";//my feeble attempts at JSON encoding$json = json_encode($paths);echo "$json: " . $json;?>

Now I would like to pass this array to a javascript function as well as a string to control a basic slideshow. My thoughts being that I could set a json_encoded array as the value of a hidden input, and use it in a way so that when the user clicks on a 'next' or 'previous' arrow, which in theory will increment or decrement the index of the array, I could use this array and indexes to set an images src. However my attempts so far have come up short.PHP 'page' (cont.)

//starts where ?> left off above<img class="pointer" src="images/arrow_right.png" onclick="slideshow('next')"><input type="hidden" id="json_catcher" value="<?php echo $json;?>"/>

JS

function slideshow(action){  alert("slideshow - going to: " + action + " picture");  var json = document.getElementById("json_catcher").value;  alert("json: " + json);  //comes out as [  alert("first index: " + json[0]); //also comes out as [};

I know what I'm trying to do is possible, but I'm kinda lost, so any thoughts? Would I'd like to be able to do is increment a decrement a javascript variable to act as a moving index to get the path of this pictures array, so I can use that path as the source for an image on the page. But my output is would suggest my implementation is wrong. Thanks for your time! :)

Link to comment
Share on other sites

This uses dojo's SlideShow:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"            "http://www.w3.org/TR/html4/strict.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>dojox Gallery / SlideShow Demo</title>    <style type="text/css">        @import "http://o.aolcdn.com/dojo/1.3/dijit/themes/tundra/tundra.css";        @import "http://o.aolcdn.com/dojo/1.3/dojo/resources/dojo.css";        @import "http://o.aolcdn.com/dojo/1.3/dojox/image/resources/image.css";... Additional style content omitted ...</style><script src="http://o.aolcdn.com/dojo/1.3/dojo/dojo..js" djConfig="parseOnLoad:true"></script><script type="text/javascript">dojo.require("dojo.parser");dojo.require("dojox.image.Gallery");dojo.require("dojo.data.ItemFileReadStore");</script></head><body class="tundra">        <h1 id="title">dojox Gallery / SlideShow Demo</h1>        <hr />        <div class="break"></div><div id="divTOC"><h2>Table Of Contents</h2><ul><?php $id=-1;if (isset($_SERVER['QUERY_STRING']) && !empty($_SERVER['QUERY_STRING'])){        $id=$_SERVER['QUERY_STRING'];        if (!is_numeric($id)) die('Go away');        $id=(int)$id;        if (!is_int($id)) die('Go away');        if (($id<0)||($id>5)) die('Go away');}$oJSON=json_decode(file_get_contents('slides/images.json'));foreach ($oJSON->items as $k => $v)        echo '<li><a href="?'.$v->id.'" title="'.$v->title.'">'.$v->title.'</a></li>';?></ul></div><div id="divGallery"><div jsId="imageItemStore" dojoType="dojo.data.ItemFileReadStore"   url="slides/images.json"></div><div id="gallery2" dojoType="dojox.image.Gallery" noLink="false"   imageWidth="400" imageHeight="300">        <div id="divLoading">        <p>Loading, please wait ...</p>        <img src="loading.gif" />        </div>  <script type="dojo/connect">    var itemRequest = {      query: {},      count: 6    };    var itemNameMap = {      imageThumbAttr: "thumb",      imageLargeAttr: "large",      linkAttr: "url",      titleAttr:"text"    };    this.slideShow.autoStart=true;    this.slideShow.titleNode=dojo.byId('divText');    this.slideShow.titleTemplate="<span style=\"float:right\" class=\"slideShowCounterText\">[${current} of ${total}]</span><br />${title}";    this.setDataStore(imageItemStore, itemRequest, itemNameMap);  </script></div></div><div id="divText"><?php if ($id != -1) echo str_repeat($oJSON->items[$id]->text.'<br />',10); ?></div><div class="break"></div>        <h2>Thanks</h2>        <p><a href="http://dojocampus.org/explorer/#Dojox_Image_Gallery_Custom%20Size">dojox Gallery</a>,              <a href="http://www.imagemagick.org/Usage/canvas/#gradient">ImageMagick gradient command</a></p></body><?phpif ($id!=-1)echo <<< SETSLIDE<script type="text/javascript">dojo.addOnLoad(function(){dijit.byId('gallery2').showImage($id);});</script>SETSLIDE;?></html>

images.json (I used gradients, because it made it easy for me to build the code.)

{"items":[{"id":"0","title":"Red","thumb":"slides/1.thumb.png","large":"slides/1.png","text":"Text for Red","url":"?detail=0"},{"id":"1","title":"Orange","thumb":"slides/2.thumb.png","large":"slides/2.png","text":"Text for Orange","url":"?detail=1"},{"id":"2","title":"Yellow","thumb":"slides/3.thumb.png","large":"slides/3.png","text":"Text for Yellow","url":"?detail=2"},{"id":"3","title":"Green","thumb":"slides/4.thumb.png","large":"slides/4.png","text":"Text for Green","url":"?detail=3"},{"id":"4","title":"Blue","thumb":"slides/5.thumb.png","large":"slides/5.png","text":"Text for Blue","url":"?detail=4"},{"id":"5","title":"Violet","thumb":"slides/6.thumb.png","large":"slides/6.png","text":"Text for Violet","url":"?detail=5"}]}

This isn't a json version, but works nicely. Put the image names in the $aImages array.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"><html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head><link rel="stylesheet" type="text/css" href="css/style.css" /></head><body><div id="header"><h1>Slideshow</h1></div><div id="main_content"><button id="btnGo" type="button" onclick="toggle()" class="floatright">Pause</button><div class="break"></div><!-- Name all the divs with div and a number, they must be sequential and they must start with 1 --><!-- You can add more divs as needed, first div is displayed, all others are display:none --><?phpecho '<div class="artwork" id="div0" style="display:block"><img src="'.$aImages[0].'" /></div>';$i=1;$l=count($aImages)-1;for (;$i<$l;$i++){echo '<div class="artwork" id="div'.$i.'" style="display:none"><img src="'.$aImages[$i].'" /></div>';}?></div><div id="footer"><p>Copyright © 2010</p></div><script type="text/javascript">var loop_pause=2000;var int=self.setInterval("rotate()",loop_pause);/* d indicates the current div */var d=1;/* newDiv is the one to be shown, firstDiv is the first in the list, and lastDiv is the last one that was shown */var newDiv,firstDiv=document.getElementById('div0');var lastDiv=firstDiv;function rotate(){/* The first div is shown on page load, so advance d */d++;/* Try to get the next div */newDiv=document.getElementById('div'+d);/* If there is no div d */if (newDiv == null){  /* Cycle back to div1, firstDiv */  newDiv=firstDiv;  /* Reset d */  d=1;}/* Hide the previous div */lastDiv.style.display='none';/* Display the new or next div */newDiv.style.display='block';lastDiv=newDiv;}var btn=document.getElementById('btnGo');function toggle(){/* Can be used to start or restart the show.  To stop it - clear the interval, to start it, reset the interval */if (btn.innerHTML=='Pause')        btn.innerHTML='Play';else        btn.innerHTML='Pause';}</script></body></html>

Link to comment
Share on other sites

thanks for the feedback wirehopper. I'll give these a good read and see what I can get out of them. How's the weather in NH? I'm heading there this weekend for a going away party. (used to live there too.)

Link to comment
Share on other sites

here, there and everywhere. I grew up in MA, spent a couple years in NH after school, now settled down in RI. should be good here for a while, I reckon.

Link to comment
Share on other sites

I've traveled to a lot of places, but never lived anywhere but good ol' WI. And I don't intend to leave. :)What does your source code look like for your hidden input line:<input type="hidden" id="json_catcher" value="<?php echo $json;?>"/>Does the JSON show up correctly there, do you reckon? :)

Link to comment
Share on other sites

it's being called via AJAX, so unfortunately I can't see what it shows, although I supposed I could try loading the page by manually passing in the arguements

Link to comment
Share on other sites

it's being called via AJAX, so unfortunately I can't see what it shows
Get FireBug (Firefox plugin), you'll see everything.NH weather has been nice lately. Lots of mosquitos, which isn't really weather, but definitely affects the outdoors.http://wirehopper.com/design/slide.php5 <--- you can see the dojox version running here.
Link to comment
Share on other sites

Get FireBug (Firefox plugin), you'll see everything.NH weather has been nice lately. Lots of mosquitos, which isn't really weather, but definitely affects the outdoors.http://wirehopper.com/design/slide.php5 <--- you can see the dojox version running here.
haha, you know I use Firebug but I never thought of clicking on the GET response in the console, :)Anyway, I can see the value that's being assigned to my hidden input.
<input type="hidden" id="json_catcher" value="["pictures\/analog\/musicfest08_web\/musicfest001.jpg","pictures\/analog\/musicfest08_web\/musicfest002.jpg","pictures\/analog\/musicfest08_web\/musicfest003.jpg","pictures\/analog\/musicfest08_web\/musicfest004.jpg","pictures\/analog\/musicfest08_web\/musicfest005.jpg","pictures\/analog\/musicfest08_web\/musicfest006.jpg","pictures\/analog\/musicfest08_web\/musicfest007.jpg","pictures\/analog\/musicfest08_web\/musicfest008.jpg","pictures\/analog\/musicfest08_web\/musicfest009.jpg","pictures\/analog\/musicfest08_web\/musicfest010.jpg","pictures\/analog\/musicfest08_web\/musicfest011.jpg","pictures\/analog\/musicfest08_web\/musicfest012.jpg","pictures\/analog\/musicfest08_web\/musicfest013.jpg","pictures\/analog\/musicfest08_web\/musicfest014.jpg","pictures\/analog\/musicfest08_web\/musicfest015.jpg","pictures\/analog\/musicfest08_web\/musicfest016.jpg","pictures\/analog\/musicfest08_web\/musicfest017.jpg","pictures\/analog\/musicfest08_web\/musicfest018.jpg","pictures\/analog\/musicfest08_web\/musicfest019.jpg","pictures\/analog\/musicfest08_web\/musicfest020.jpg","pictures\/analog\/musicfest08_web\/musicfest021.jpg","pictures\/analog\/musicfest08_web\/musicfest022.jpg","pictures\/analog\/musicfest08_web\/musicfest023.jpg","pictures\/analog\/musicfest08_web\/musicfest024.jpg","pictures\/analog\/musicfest08_web\/musicfest025.jpg","pictures\/analog\/musicfest08_web\/musicfest026.jpg","pictures\/analog\/musicfest08_web\/musicfest027.jpg","pictures\/analog\/musicfest08_web\/musicfest028.jpg","pictures\/analog\/musicfest08_web\/musicfest029.jpg","pictures\/analog\/musicfest08_web\/musicfest030.jpg","pictures\/analog\/musicfest08_web\/musicfest031.jpg","pictures\/analog\/musicfest08_web\/musicfest032.jpg","pictures\/analog\/musicfest08_web\/musicfest033.jpg","pictures\/analog\/musicfest08_web\/musicfest034.jpg","pictures\/analog\/musicfest08_web\/musicfest035.jpg","pictures\/analog\/musicfest08_web\/musicfest036.jpg","pictures\/analog\/musicfest08_web\/musicfest037.jpg","pictures\/analog\/musicfest08_web\/musicfest038.jpg","pictures\/analog\/musicfest08_web\/musicfest039.jpg","pictures\/analog\/musicfest08_web\/musicfest040.jpg","pictures\/analog\/musicfest08_web\/musicfest041.jpg","pictures\/analog\/musicfest08_web\/musicfest042.jpg","pictures\/analog\/musicfest08_web\/musicfest043.jpg","pictures\/analog\/musicfest08_web\/musicfest044.jpg","pictures\/analog\/musicfest08_web\/musicfest045.jpg"]"/>

Thanks for the insight wirehopper! Looks like you joined just in time. (to help me out, hehe) :) Now to examine what this means.... :)

Link to comment
Share on other sites

value="["pictures...That first quote is breaking the string, so you'll need to add slashes before double quotes to get that to work.
darn quotes! the bane of my existance, as you have come to find out with me JSG! Thanks for the tip, looking forward to giving it a whirl. :)edit: do you mean all quotes within the value ($json) or just the quotes used for value itself?
Link to comment
Share on other sites

All of the quotes in the value need to be escaped so that they don't prematurely end the value attribute... value.It's been a while since I've messed with HTML much, so I'm actually not sure if it's correct to put a slash before the quotes or replace them with ".

Link to comment
Share on other sites

It's been a while since I've messed with HTML much, so I'm actually not sure if it's correct to put a slash before the quotes or replace them with ".
I'm pretty sure it's invalid to have slashes. Well not invalid but that's not escaping them. But regardless I don't think that either of those ways are going to work well for what scientist is trying to do. They both would require parsing in JavaScript.
Link to comment
Share on other sites

Technically, no. Some implementations might support them, but according to json.org the definition of a string is a double-quoted one.
Well then it might work the other way. Single for value, double in JSON.
Link to comment
Share on other sites

They both would require parsing in JavaScript.
I don't think so, I think using " is telling the browser that there's a double-quote there, and when it submits the form the value will actually have the double quote instead of the entity name.
Link to comment
Share on other sites

I don't think so, I think using " is telling the browser that there's a double-quote there, and when it submits the form the value will actually have the double quote instead of the entity name.
Indeed you are correct sir. I admit defeat... :)But it would still work to use singles for the value and doubles in the JSON...value='["pictures....
Link to comment
Share on other sites

Indeed you are correct sir. I admit defeat... :)But it would still work to use singles for the value and doubles in the JSON...value='["pictures....
thanks for the help everyone! I've now made it one step further. The JSON string now appears in the alert statement when clicking on a button and pulling the hidden inputs value (the JSON encoded string), which, I might add was quite hilarious because the alert box grew to be taller than the page and i could only hit enter because the bottom of it was pushed so far down and off my screen, :)However, I think i may be in predicament because I can only read json, not json[0], as it appears all the images are just stored in a comma seperated array [], not a numerical array liked I had made in PHP where
$paths[0] = images/..../pic1.jpg, $paths[1] = images/..../pic2.jpg, etc.

So should I construct a better object in PHP and create a multi-demensional array where

$json[0] = {   "img1": "images/.../pic1.jpg",   "img2": "images/.../pic2.jpg"  etc}

Or should I do all my parsing in Javascript and just create a new array there? Thanks again for everyone's help! :)

Link to comment
Share on other sites

When you convert the JSON string back to an array, it will number everything. JSON is the native notation for objects in Javascript, you can define an array like this in PHP and Javascript, they'll create the same structure:

$ar = array(  'one',  'two',  'three');

var ar = [  'one',  'two',  'three'];

So if your JSON looks like this:["pictures\/analog\/musicfest08_web\/musicfest001.jpg","pictures\/analog\/musicfest08_web\/musicfest002.jpg","pictures\/analog\/musicfest08_web\/musicfest003.jpg"]Then that will represent an array where ar[0] is the first image, ar[1] is the second, etc.If you can guarantee that the JSON string will never contain malicious code (if you have complete control over the data which gets printed in that string), then you can just use eval to turn your string into an array or object:eval('var ar = (' + json + ')');The extra parens there are necessary. That statement will turn your string called json into an object called ar.

Link to comment
Share on other sites

When you convert the JSON string back to an array, it will number everything. JSON is the native notation for objects in Javascript, you can define an array like this in PHP and Javascript, they'll create the same structure:
$ar = array(  'one',  'two',  'three');

var ar = [  'one',  'two',  'three'];

So if your JSON looks like this:["pictures\/analog\/musicfest08_web\/musicfest001.jpg","pictures\/analog\/musicfest08_web\/musicfest002.jpg","pictures\/analog\/musicfest08_web\/musicfest003.jpg"]Then that will represent an array where ar[0] is the first image, ar[1] is the second, etc.If you can guarantee that the JSON string will never contain malicious code (if you have complete control over the data which gets printed in that string), then you can just use eval to turn your string into an array or object:eval('var ar = (' + json + ')');The extra parens there are necessary. That statement will turn your string called json into an object called ar.

eval() was the key!!! :)it shall be a good weekend :)
Link to comment
Share on other sites

You could create an object in javascript, exactly as you want it to be, and use FireBug to verify it. Then change your PHP to create the JSON in that format.Be sure to use POST to get the values.

Link to comment
Share on other sites

eval() was the key!!! :)it shall be a good weekend :)
I had the same trouble a while back. I didn't take into account that the JSON string I was working with was exactly that, a string. Guess it happens to the best of us, eh? :)
Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...