jQuery: AJAX image gallery

So far we've seen AJAX content generated after a successful request triggered by a call-to-action. But this kind of content can actually be generated when the page is finished loading. A typical example is an image gallery retrieved from a server-side script like this:

header('Content-Type: text/xml');
  $xml = '<?xml version="1.0" encoding="utf-8"?>';
  $xml .= '<gallery>' . "\n";
  
  $dir = opendir('books');
  $images = array();
  
  while($fname = readdir($dir)) {
     
     if(preg_match('/[.]gif$/', $fname)) {
         
         $images[] = $fname;
         
     }
     
     
     
 }  
 
 closedir($dir);
 
 function imgSort($a, $b)
 {
     $a1 = str_replace('.gif', '', $a);
     $a2 = str_replace('.gif', '', $b);
     
     return $a1 > $a2;
     
 }
 
 usort($images, 'imgSort');
 


 
 foreach($images as $img) {
     
     $xml .= '<img>books/' . $img . '</img>' . "\n";
     
 }
 
 $xml .= '</gallery>';
 
 echo $xml;

This PHP script generates an XML file containing a list of images. We can fetch this file using jQuery, like so:

$(document).ready(function() {

    $('<ul id="gallery"></ul>').appendTo('body');
    var html = '';
    
    $.ajax({
        type: 'GET',
 url: 'gallery.php',
 dataType: 'xml',
 data: null,
 success: function(xml) {
 
     $(xml).find('img').each(function() {
     
         var url = $(this).text();
  html += '<li><img src="' + url + '" /></li>';
  
     
     
     });
     
     $('#gallery').html(html);
 
 
 }
 
    });

});

The above code generates an unordered list that contains all of our images. As you can see, the AJAX request takes place when the page is ready and without a call-to-action. You can see this demo here.

This entry was posted in by Gabriele Romanato. Bookmark the permalink.

Leave a Reply

Note: Only a member of this blog may post a comment.