bdrelling
bdrelling

Reputation: 840

How do I count files in a directory using jQuery?

I'd like to count the number of files in a folder and return that number to set a variable in a .js file.

Essentially, I have X number of images in a folder. When the user clicks the right arrow, I replace the existing set of 8 images with the next set of 8 images, and so on and so forth. I currently manually enter the variable (38 right now) into the page, since there are 38 thumbnails in the folder.

The code works perfectly, but I hate the idea of changing a number each time I add a file. I'd like to have it set the variable to the exact number of images in the folder.

Is this possible using JavaScript or jQuery? Do I need to write a PHP file to do return this variable for me? Any information would be great!

Upvotes: 1

Views: 15146

Answers (4)

Oscar Jara
Oscar Jara

Reputation: 14187

Simple way:

<?php
    $dir = "images";
    $file_count = count(glob("{$dir}/*.*"));
?>
<html>
<head>
<title>Welcome</title>
</head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){ 

    var dir = <?php echo $dir ?>;
    var file_count = <?php echo $file_count ?>;

    $('#msg').html('File count in folder ' + dir + ' is ' + file_count);
});
</script>
<body>
<div id="msg"></div>
</body>
</html>

Upvotes: 2

mplungjan
mplungjan

Reputation: 177851

If you must use client side and the files are numbered, preload the file and set the number when you get an error

...
Img = new Image();
Img.onerror=function() {
  maxImages=cnt-1;
}
Img.src = "image_"+cnt+".jpg";

Upvotes: 3

Adam Fowler
Adam Fowler

Reputation: 1751

I would do it like this

echo count(glob("{$_GET['dir']}/*.*"));

Upvotes: 0

Mendhak
Mendhak

Reputation: 8775

This is the kind of task PHP is better suited for, keep your Javascript to the client-side. Write a very simple PHP script that counts the files in a folder

echo iterator_count(new DirectoryIterator('/home/path/dir'));

And call it from your JQuery script.

$.get('numberoffiles.php', function(data) {
  alert(data);
});

Upvotes: 8

Related Questions