retrieve all images using ajax

function checkallfolder(){
  var thumbnailbox = $('#thumbnailbox');
  var foldertype = ["img1", "img2", "img3", "img4", "img5", "img6", "img7"];
  for (var c = 0; c < foldertype.length; c++ ){
    var folder = 'Img/dfolder/'+foldertype[c];
    $.ajax({
      type : "POST",
      url: "data.php",
      contentType:"application/x-www-form-urlencoded",
      dataType: "json",
      data: "folder="+folder,
      success: function(d) {
        var temp = '';
        thumbnailbox.html('');
        for (var obj in d){
          if (d.hasOwnProperty(obj) && d[obj].hasOwnProperty('src') && d[obj].src !== ''){
            var objname = d[obj].name;
            temp += "<div><img name="+d[obj].name+" class='icon' src="+d[obj].src+"></div>";
            console.log(d[obj].src);
          }
        }
        thumbnailbox.html(temp);
      }
    });
  }
}

I am making an AJAX request to check all folders inside an image directory. I use a loop with "for" to iterate through the folders, and I can see in the console log that it is going through all 7 folders and retrieving the objects. However, when I try to display them as "img" elements with "src" attribute, only the last image (folder7/img7) is showing up. I have confirmed that all the "src" values are being fetched, so I should be getting all the images. Can someone help me figure out what is wrong with my code?

Answer №1

Utilizing closure is key in this scenario.

Challenge:

In JavaScript, variables have function-level scope. When using AJAX (Asynchronous call) within a loop, the loop will continue executing regardless of the AJAX response. This results in the local variable being overwritten each time, causing the variable c to always refer to the value from the last loop iteration.

To address this issue, make foldertype a global variable by moving it outside the function:

 var foldertype = ["img1", "img2", "img3", "img4", "img5", "img6", "img7"];

Then, modify your checkallfolder() function as follows:

...
for (var c = 0; c < foldertype.length; c++){
var folder = getImageSrc(c);
...

Additionally, create an getImageSrc function like this:

function getImageSrc(c){
   return 'Img/dfolder/'+foldertype[c];
}

After implementing these changes, your code should look like this:

var foldertype = ["img1", "img2", "img3", "img4", "img5", "img6", "img7"];


function checkallfolder(){
      var thumbnailbox = $('#thumbnailbox');
      for (var c = 0; c < foldertype.length; c++){
          var folder = getImageSrc(c);
          $.ajax({
                ...ajax code here...
          });
       }
}

function getImageSrc(c){
   return 'Img/dfolder/'+foldertype[c];
}

Answer №2

Create an array and add the value "temp" to it. Then, assign arr.toString() to thumbnailbox.html()

function checkAllFolders(){
    var thumbnailBox = $('#thumbnailbox');
    var folderType = ["img1", "img2", "img3", "img4", "img5", "img6", "img7"];
    for (var c = 0; c < folderType.length; c++){
        var folder = 'Img/dfolder/' + folderType[c];
        var arr = new Array();
        $.ajax({
            type: "POST",
            url: "data.php",
            contentType: "application/x-www-form-urlencoded",
            dataType: "json",
            data: "folder=" + folder,
            success: function(data){
                var temp = '';
                thumbnailBox.html('');
                for (var obj in data){
                    if (data.hasOwnProperty(obj) && data[obj].hasOwnProperty('src') && data[obj].src !== ''){
                        var objName = data[obj].name;
                        temp += "<div><img name=" + data[obj].name + " class='icon' src=" + data[obj].src + "></div>";
                        arr.push(temp);
                        console.log(data[obj].src);
                    }
                }
                //thumbnailBox.html(temp);
            }
        });
    }
    thumbnailBox.html(arr.toString().replace(/,/g, ""));
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Send an AJAX request to redirect to a different page on a PHP server

After collecting data from JavaScript, my page transfers it to PHP and then MySQL. The issue arises when I want the page to redirect to different pages based on the database content. I attempted to use the header function, but it only displayed the entire ...

Activate divs with Bootstrap5 modal toggle functionality

What adjustments must be made to the Bootstrap 5 example below in order to achieve the following two objectives: The "afterAcceptingTerms" division should remain hidden until the user clicks on the Accept Terms modal button, ensuring that only the "before ...

Why do two date type variables have identical content?

I'm trying to grasp why the value of d1 changes in each alert(). Any insights would be greatly appreciated. Thanks! <script> d1 = new Date("01/01/2015"); d2 = d1; alert(d1); d2.setDate(d2.getDate()+10); alert(d1); </script> ...

Transfer an image using an ajax form using Python and Selenium

As I dive into the world of selenium, I set my sights on experimenting with facebook to automate filling out my profile using selenium. However, Facebook utilizes a lot of ajax, making the process a bit more challenging. While entering details like my ho ...

Fixing the errors outlined below

After integrating the spectrum color picker, I'm currently working on resolving the JSLint errors that have appeared. There are two specific types of errors that I'm struggling to rectify. Here they are: Unexpected '~' Unexpect ...

Attempting to conditionally map an array of objects

I am currently working on conditionally rendering content on a screen. My main task involves manipulating an array of 3 objects with sub-objects, stored as the initial state in my reducer (using dummy data). The layout includes a customized SideNav bar wit ...

AngularJS module dependencies configuration functions smoothly during initialization

The structure of my modules looks like this: angular.module('mainModule',["cityModule", "countryModule"]); angular.module('mapModule',[]); angular.module('cityModule',["mapModule"]); angular.module('countryModule',[ ...

What is the best way to retrieve AWS secret values using JavaScript?

Having recently started using AWS, I have been able to manually obtain the secret I need. However, when attempting to utilize the code snippet provided by AWS to retrieve the secret value, all my attempts result in undefined. Can someone please point out ...

The HTML generated by Selenium using Javascript is still missing some elements, despite accessing the document.body.innerHTML

Attempting to retrieve the HTML from a webpage that undergoes modification by JavaScript post-loading. Followed directions in this guide, executing the command below in my Python script after initial page load: html = browser.execute_script("return docume ...

What is the best way to display toastr messages in an Angular application?

Can you guide me on how to include toastr in an angular app? Currently, I am enrolled in the Angular Fundamentals course and trying to use toastr.success within my export class: handleThumbnailClick(eventName){ toastr.success(eventName) } But, I kee ...

Tips on organizing and designing buttons within a canvas

let canvas = document.getElementById("canvas"); let context = canvas.getContext("2d"); // for canvas size var window_width = window.innerWidth; var window_height = window.innerHeight; canvas.style.background="yellow" canvas.wid ...

Utilizing _.partial on a single-argument function

Currently, I am in the process of refactoring code within a react.js application. There is an element that utilizes Underscore.js _.partial on a function that already has one argument. Is there any real benefit to doing this? I can see how it works based ...

Using remote: true with select_tag in Rails allows the select menu to dynamically

When I call an AJAX function from a select_tag like this: <%= select_tag 'quantity', options_from_collection_for_select(order.options), :quantity, :quantity, order.quantity), onchange: "update_price(#{order.id}, this.value);" %> Here is t ...

jQuery is an excellent tool for implementing drag and drop folder upload functionality, all without

I am creating a drag and drop file uploader with basic functionality. Here is the code: HTML: <div class="drop-box drop-area"> <form enctype="multipart/form-data" id="yourregularuploadformId"> <input type="file" name="files[]" ...

Trouble with the Ajax search feature in Laravel

No data is currently being displayed; console:finished loading: GET "http://todolist.local/teachers/search?text=a". I am attempting to display results in the tbody when a user types something in the search bar. Ajax code: <script> $(document).rea ...

Python code that extracts data from an AJAX website

Looking to scrape a website that includes a directory of individuals and their details. The issue arises when the site uses ajax to load new information as I continue scrolling down. I'm in need of data for every single person on the list. The urllib ...

Angular causing WKWebview to freeze

Situation Our Angular+Bootstrap app is functioning smoothly in Desktop on all operating systems, as well as Android and iPhone devices. There are no visible JavaScript errors or CSS warnings. Dilemma However, an issue arises intermittently while using t ...

What causes req.sessions to show an empty object instead of the expected value?

I've been grappling with a small issue while learning express.js. I am struggling to save sessions in the browser so that users don't have to log in every time they visit. I am using cookie-session for this purpose. When I send the login data fro ...

In Stripe.js, the background color and height of the credit card input cannot be customized

I'm struggling with customizing the appearance of a Stripe credit card input within my Vue.js application. I want to adjust the background color to #f1f1f1 and set the height to 60px, but despite trying both base styles and css, I can't seem to g ...

Having trouble locating an element on a webpage? When inspecting the element, are you noticing that the HTML code differs from the source page?

I'm having trouble locating a specific element on a webpage. When I use the Inspect Element tool, I can see the HTML code with the element id = username, but when I check the page source, all I see is JavaScript code. Does anyone have any suggestions ...