Skip to content Skip to sidebar Skip to footer

How Do I Fetch All Images In A Folder With Ajax Using Pure Js?

I'm trying to get all the images in a folder with an AJAX request (for use in an image slider). I've found this jQuery solution which works perfectly fine, except that it uses jQue

Solution 1:

Thanks to @FZs help this is what I ended up with. Thank you!

var xhr = newXMLHttpRequest();
xhr.open("GET", "/img", true);
xhr.responseType = 'document';
xhr.onload = () => {
  if (xhr.status === 200) {
    var elements = xhr.response.getElementsByTagName("a");
    for (x of elements) {
      if ( x.href.match(/\.(jpe?g|png|gif)$/) ) { 
          let img = document.createElement("img");
          img.src = x.href;
          document.body.appendChild(img);
      } 
    };
  } 
  else {
    alert('Request failed. Returned status of ' + xhr.status);
  }
}
xhr.send()

Solution 2:

You can do it without jQuery! Maybe with more code, but this should work (adapted from this post)):

var folder = "images/";
    var ajax=newXMLHttpRequest()
    ajax.open("GET",folder,true)
    ajax.onload=function () {
        var elements=(newDOMParser()).parseFromString(ajax.responseText,"text/html").getElementsByTagname("A")
        for(x of elements){
            if(request.status[0]==2 && x.href.match(/\.(jpe?g|png|gif)$/)) { 
                let img=document.createElement("IMG")
                img.src=folder+x.hrefdocument.body.appendChild(img);
            } 
        };
    }
    ajax.send()

Or, you can force XMLHttpRequest to parse document (idea from @Rainman's comment):

ajax.responseType = "document"

So the code becomes to the following:

var folder = "images/";
    var ajax=newXMLHttpRequest()
    ajax.open("GET",folder,true)
    ajax.onload=function () {
        ajax.responseType="document"var elements=ajax.responseText.getElementsByTagname("A")
        for(x of elements){
            if(request.status[0]==2 && x.href.match(/\.(jpe?g|png|gif)$/)) { 
                let img=document.createElement("IMG")
                img.src=folder+x.hrefdocument.body.appendChild(img);
            } 
        };
    }
    ajax.send()

Post a Comment for "How Do I Fetch All Images In A Folder With Ajax Using Pure Js?"