0

I am new to Stackoverflow, I am learning Javascript and Ajax, I know how to open connections using Ajax but I have no idea how to use Ajax to load images from a specific directory in the same server. I have googled Javascript and Ajax tutorials to load images from a directory using Javascript and no jQuery but i am unable to find any good tutorials since most of them use jQuery. I want to display images from a folder into a HTML div, is it possible to do it without using jQuery?

Saw it in the comments and realized that i should edit the question. I would like to load several images in one folder without having to manually type them in HTML. I am able to use the DOM to select files manually but I need to display several images without having to repeat too much HTML code.

3
  • jQuery is just a library of javascript. If you can do it in jQuery, you can do it in plain javascript, albeit usually in a less new-user friendly manner. Commented Apr 24, 2014 at 13:24
  • <img src="your/folder/image"> Commented Apr 24, 2014 at 13:25
  • I don't suppose your task involves getting the list of all images in a directory? That part might be more complex and you'd want to mention that specifically. Commented Apr 24, 2014 at 13:26

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

2

You don't really have to "load" the images.

You can make an Ajax request, which get the source of the image you want (ex. 'image.png') and then insert the image in your html.

Here's a code sample:

<script type="text/javascript">

   //xhr object
   var xhr = new XMLHttpRequest();
   //function called when ajax request return something
   xhr.onreadystatechange = function(){
      if(xhr.readyState == 4 && xhr.status == 200)
      {
         //get the returned image source
         var img_src = xhr.responseText;
         //insert the image in a div
         document.getElementById('my_div').innerHTML = '<img src="' + img_src + '" />';
      }
   }
   //open the wanted page
   xhr.open('POST', 'my_page.php', true);
   //ajax headers
   xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
   //send parameters
   xhr.send('some_param='+param_value);

</script>

5 Comments

I am getting this error. Uncaught ReferenceError: param_value is not defined
This was an example :) If you don't want to set parameters, just let xhr.send(); empty. Everytime I wrote something like 'my_div' or 'my_page', you have to replace those with your values, as they are examples.
I am still unable to do it because i want to get images from a directory, the directory is named images, I used your code and replaced 'mypage.php' with the name of the directory 'images' but it doesn't display the images. I assume it's because there's no .php extension given, if possible please let me know how to get it from the directory. :)
Ok, first of all, Ajax requests target PHP files. When you send the request, the PHP script you targeted is running and then send you a return value (here, the image source obviously). So you have to get and return (with an echo for example) the image source in your PHP target file. For example, make a image.php file in your images folder, in which you get the image source, then use echo $file_source to return the value to your Ajax script. Finally, you should read articles and tutorials about Ajax request as you don't seem to be very used to it. :)
The W3C documentation on Ajax request should help you undestand all of this. Here it is: w3schools.com/ajax/ajax_intro.asp Good luck

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.