1

Short Version Need help creating a variable that stores the number of files in a folder and then use it as a loop counter.

Full Version: I thought I found my answer HERE, but it isn't working for me. Since I don't have enough reputation, I can't comment on that old thread so here I am.

I created a JQuery function to add images to a portfolio page. It is:

$(document).ready(function() {
   for (i = 1; i <= 9; i++) {
      $('.flex-container').append('<aside class="flex-item"><img src="images/portfolio/' + i + '.jpg" alt="blah blah"></aside>');
   }
});

As you can see, I started with 9 images. However, I'd like the site to automatically update when additional images are added to the 'images/portfolio' folder. (Images are named in numerical order such as 1.jpg, 2.jpg, etc.)

Based on the thread I linked to above, I created a php file named numberoffiles.php. That file contains:

<?php 
   return iterator_count(new DirectoryIterator('../images/portfolio'));
?>

(My root directory contains both the 'images' and 'scripts' folder these files are contained in.)

I edited my js file to this:

$(document).ready(function() {
    $.get('numberoffiles.php', function(data) {
        var count = data;
    });
    for (i = 1; i <= count; i++) {
        $('.flex-container').append('<aside class="flex-item"><img src="images/portfolio/' + i + '.jpg" alt="blah blah"></aside>');
    }
});

I tried it both with the $.get code inside and outside of the $(document).ready(function), but neither worked.

Something tells me I'm missing something very simple here.

Community
  • 1
  • 1

1 Answers1

1

It's simple. The AJAX data was not received when you iterate with for(). You can use promises or deferred, or simply $.ajax function with GET parameters.

You can try this without change your code:

$(document).ready(function() {
    $.get('numberoffiles.php', function(data) {
        var count = data;

        for (i = 1; i <= count; i++) {
             $('.flex-container').append('<aside class="flex-item"><img src="images/portfolio/' + i + '.jpg" alt="blah blah"></aside>');
        }
    });
});

Good luck.

Marcos Pérez Gude
  • 21,869
  • 4
  • 38
  • 69