Multiple Album Photo Gallery Ajax PHP JSON Tutorial

Published :
Author :
Adam Khoury
In this lesson we demonstrate how to extend our basic gallery into a very lightweight multiple album dynamic photo gallery using Ajax, PHP and JSON. json_gallery_data.php <?php header("Content-Type: application/json"); $folder = $_POST["folder"]; $jsonData = '{'; $dir = $folder."/"; $dirHandle = opendir($dir); $i = 0; while ($file = readdir($dirHandle)) { if(!is_dir($file) && preg_match("/.jpg|.gif|.png/i", $file)){ $i++; $src = "$dir$file"; $jsonData .= '"img'.$i.'":{ "num":"'.$i.'","src":"'.$src.'", "name":"'.$file.'" },'; } } closedir($dirHandle); $jsonData = chop($jsonData, ","); $jsonData .= '}'; echo $jsonData; ?> JSON_tutorial_6.html <!DOCTYPE html> <html> <head> <style> body { margin:0px; background:#000; color:#CCC; } div#pagetop { position:fixed; background: #333; padding:20px; font-size:36px; width:100%; border-bottom:#000 1px solid; } div#thumbnailbox { float:left; margin-top:82px; width:120px; background:#292929; } div#thumbnailbox > div { width:100px; height:80px; overflow:hidden; margin:10px; cursor:pointer; } div#thumbnailbox > div > img { width:100px; } div#pictureframe { position:fixed; left:140px; top:100px; width:700px; text-align:center; } div#pictureframe > img { max-width:700px; } div#albummenubox { position:fixed; left:856px; top:100px; width:200px; background:#CCC; padding:12px; color:#000; border-radius: 10px; } </style> <script> function ajax_json_gallery(folder){ var thumbnailbox = document.getElementById("thumbnailbox"); var pictureframe = document.getElementById("pictureframe"); var hr = new XMLHttpRequest(); hr.open("POST", "json_gallery_data.php", true); hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); hr.onreadystatechange = function() { if(hr.readyState == 4 && hr.status == 200) { var d = JSON.parse(hr.responseText); pictureframe.innerHTML = "<img src='"+d.img1.src+"'>"; thumbnailbox.innerHTML = ""; for(var o in d){ if(d[o].src){ thumbnailbox.innerHTML += '<div onclick="putinframe(\''+d[o].src+'\')"><img src="'+d[o].src+'"></div>'; } } } } hr.send("folder="+folder); thumbnailbox.innerHTML = "requesting..."; } function putinframe(src){ var pictureframe = document.getElementById("pictureframe"); pictureframe.innerHTML = '<img src="'+src+'">'; } </script> </head> <body> <div id="pagetop">Dynamic JSON Ajax PHP Driven Image Gallery</div> <div id="thumbnailbox"></div> <div id="pictureframe"></div> <div id="albummenubox"> <h3>My Photo Albums</h3> <a href="#" onclick="return false" onmousedown="ajax_json_gallery('gallery1')">Gallery 1</a><br> <a href="#" onclick="return false" onmousedown="ajax_json_gallery('gallery2')">Gallery 2</a><br> <a href="#" onclick="return false" onmousedown="ajax_json_gallery('gallery3')">Gallery 3</a><br> </div> <script>ajax_json_gallery('gallery1');</script> </body> </html>