Forums

The forums ran from 2008-2020 and are now closed and viewable here as an archive.

Home Forums JavaScript Populate list with directory contents Reply To: Populate list with directory contents

#148235
Willson
Participant

You won’t be able to do this with just javascript, it will not allow you to query a folder. However you could get it working with a fairly simple php script that returns a json object that you can parse with javascript.

<?php

$files = array();
$dir = opendir('.');
while(false != ($file = readdir($dir))) {
        if(($file != ".") and ($file != "..") and ($file != "directory.php")) {
//make sure the file isn't directory or this file
                $files[] = $file; // put in array.
        }
}

natsort($files); // sort.
$end = end($files);
// print.
echo("[");
foreach($files as $file) {

    if ($end !== $file){
        echo("{\"file\": \"$file\" },");
    }else{

        echo("{\"file\": \"$file\" }");

    }
}
echo("]");

?>

note that “directory.php” will be whatever you name this file.

If you save that, and drop it in to the folder you have your files in you should be able to do an ajax call with JQuery.

ie: $.getJSON('directory/directory.php', function(data){ console.log(data); });