jQuery: AJAX directory listing

jQuery: AJAX directory listing

An AJAX-enabled directory listing implemented with jQuery.

Implementing an AJAX directory listing with jQuery requires the use of a server-side script which processes the contents of a directory (passed as a GET parameter) and returns an HTML output. jQuery simply fetches this HTML output after sending the name of the directory to be processed to the server-side script.

To begin with, here's our initial markup structure:


<p><a href="ajax-listing.php?dir=jquery" id="view">View listing</a></p>
<div id="listing"></div>

The query string is embedded in the link's URL due to accessibility reasons: if JavaScript is disabled, a user can always view the directory listing as a plain HTML document.

Here's our server-side script, written in PHP:


<?php
header('Content-Type: text/html');
$dir = $_GET['dir'];
$start = '';

if(preg_match('/^[a-z0-9-_]+$/', $dir)) {

	$start = $dir;

} else {

	echo '<p>Error</p>' . "\n";
	exit();


}

function directoryIteratorToArray(DirectoryIterator $it) 
{
    $result = array();
    foreach ($it as $key => $child) {
        if ($child->isDot()) {
            continue;
        }
        $name = $child->getBasename();
        if ($child->isDir()) {
         $js = strpos($name, 'js');
         if($js === false) {
            $subit = new DirectoryIterator($child->getPathname());
            $result[$name] = directoryIteratorToArray($subit);
            
         }
        } else {
        
         if(!preg_match('/^\./', $name)) {
            $result[] = $name;
            
         }
        }
    }
    return $result;
}

$files = directoryIteratorToArray(new DirectoryIterator($start));
$html = '<ul>' . "\n";
$base = 'http://' . $_SERVER['HTTP_HOST'] . '/esempi/corso-jquery/';

foreach($files as $dir => $contents) {

    $html .= '<li>/' . $dir . '/';
    $html .= '<ul>';
    
    foreach($contents as $file) {
    
    	$html .= '<li><a href="' . $base . $dir . '/' . $file . '">' . $file . '</a></li>';
    
    }
    
    $html .= '</ul>';
    
    $html .= '</li>';




}

$html .= '</ul>';

echo $html;
?>

Our PHP code makes use of the DirectoryIterator class to process all the contents of the directory passed via the GET parameter dir. With jQuery we have only to send the correct query string and display the HTML output:


$(function() {

	$('#view').click(function(event) {
	
		event.preventDefault();
		
		var $a = $(this);
		var href = $a.attr('href');
		var query = href.substring(href.indexOf('?'), href.length);
		
		$.ajax({
			url: href,
			dataType: 'html',
			type: 'GET',
			data: query,
			success: function(html) {
			
				$('#listing').html(html);
			
			}
		});
	
	
	});


});

You can see the demo in the following video.