You don't need to use JavaScript to load images from a folder on your web server. You just need to make sure your images are in a publicly accessible folder on your web server and include them on your HTML/PHP pages using img tags:
<img src="path/to/image.jpg" alt="image" />
However, if you want to load a list of images dynamically, with a library like knockout.js, you can load JSON containing a collection of images and then bind the collection to your HTML like this:
<div data-bind="foreach: images">
<img data-bind="attr: { src: $data }" alt="image" />
</div>
The JSON from the server would look something like this:
["path1", "path2"]
You would have something like this for your PHP:
<?php
$directory = '/path/to/files';
if ( ! is_dir($directory)) {
exit('Invalid diretory path');
}
$files = array();
foreach (scandir($directory) as $file) {
if ('.' === $file) continue;
if ('..' === $file) continue;
$files[] = $file;
}
echo json_encode($files);
?>
Then you would have a JavaScript viewModel that looks like this:
var viewModel = function() {
var self = this;
self.images = ko.observableArray();
self.loadImages = function() {
var xmlhttp;
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else {// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
var data = JSON.parse(xmlhttp.responseText);
for(var i = 0; i < data.length; i++) {
self.images.push(data[i]);
}
}
}
xmlhttp.open("GET","getimages.php",true);
xmlhttp.responseType = 'json';
xmlhttp.send();
}
return self;
}();
ko.applyBindings(viewModel);
The beauty of using knockout.js is that it takes care of the DOM updating automatically when your viewModel changes. You don't have to explicitly remember element ids and remove them from the DOM should they be removed from your viewModel.
<img src="your/folder/image">