You may adopt one of 2 Possibilities... Option Nr. 1: You can expose the Number of Images as a Global Variable & Use it in your main.js (that is Assuming that main.js was included in the numberOfImages.php Script. Option Nr. 2 You can use Ajax to do that too:
OPTION NR. 1
<?php
//FILE =>numberOfImages.php:
$dir = "/my/directory/";
$fi = new FilesystemIterator($dir, FilesystemIterator::SKIP_DOTS);
$fileCount = iterator_count($fi);
// EXPOSE THIS VARIABLE TO JAVASCRIPT AS A GLOBAL VARIABLE..
//echo $fileCount;
?>
// SOMEWHERE IN THE SAME FILE: numberOfImages.php:
<script type="text/javascript">
var _NUM_IMAGES = "<?php echo $fileCount; ?>";
</script>
Now, you can access the Number of Images in the main.js by simply referencing the variable _NUM_IMAGES. So doing alert(__NUM_IMAGES) would work. However, be Sure that the main.js is included in the numberOfImages.php File
OPTION NR 2
// INSIDE YOUR HTML/PHP FILE THAT RUNS THE SHOW; IMPORT BOTH JQUERY & YOUR main.js BELOW.
// INCLUDE JQUERY LIBRARY: OTHERWISE THIS WON'T WORK...
// SURE YOU CAN ALSO DO ALL THESE IN PURE JAVASCRIPT, BUT WHY RE-INVENT THE WHEEL???
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.3/jquery.min.js"></script>
<script type="text/javascript" src="main.js"></script>
//YOUR main.js COULD LOOK SOMETHING LIKE THIS:::
jQuery.noConflict();
(function ($) {
$(document).ready(function(e) {
$.ajax({
url: 'numberOfImages.php', // <== POINTS TO THE VALID URL OF THE PHP FILE THAT OUTPUTS THE NUMBER OF IMAGES...
dataType: "HTML",
cache: false,
type: "POST",
//HANDLE THE SUCCESS CASE FOR THE AJAX CALL
success: function (data, textStatus, jqXHR) {
if(data){
alert(data);
}
},
//HANDLE THE FAILURE CASE FOR THE AJAX CALL
error: function (jqXHR, textStatus, errorThrown) {
console.log('The following error occured: ' + textStatus, errorThrown);
},
//HANDLE THE EVENT-COMPLETE CASE FOR THE AJAX CALL
complete: function (jqXHR, textStatus) {
}
});
});
})(jQuery);
And the numberOfImages.php could look something like this. Exactly the same way you did it:
<?php
/**
* filename: numberOfImages.php
*/
$dir = "/my/directory/";
$fi = new FilesystemIterator($dir, FilesystemIterator::SKIP_DOTS);
$fileCount = iterator_count($fi);
die($fileCount);
However, be informed that You need JQuery for this to work. You can add this to the File in which you are importing the main.js but before you import the main.js.