2

I want to have a javascript variable that is equal to the amount of pictures in the directory where the javascript file is.

There are 2 things I don't know how to do:

1) Get the number of images in the folder using PHP.

2) Transfer this data to javascript.

There are many versions of each of the steps online, but I don't understand how to combine them and I don't know which way to choose.

Please help me understand what I need to do in order to get these 2 done.

OriShuss
  • 269
  • 2
  • 3
  • 14

1 Answers1

2
  1. For couting number of images into folder,
$imgs = scandir($dir);
$f = count($imgs);
echo $f;

2 . get value into js variable.

Now for that make ajax call to php and write step first code and into success callback of ajax set js variable value to the response you received from php code.

For couting images you can also use different code.

Count how many files in directory php

Example

create new php file and name it whatever you want, but for this example i am giving it ajax.php and i will demonstrate you jQuery example code.

now in ajax.php file write below code.

$imgs = scandir($dir);
$f = count($imgs);
echo $f;

now in index.php file add below code,

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
    $(function()
    {
        var jsvar;

        $.ajax(
        {
            url : 'ajax.php',
            type : 'get',
            success : function(response)
            {
                jsvar = response;
            }
        });
        alert(jsvar);
    });
</script>

after pasting above code and save it and run in browser, you will see alert showing count of total number of images it have.

jsvar is the javascript variable that you want to store total images count.

Community
  • 1
  • 1
Dipesh Parmar
  • 27,090
  • 8
  • 61
  • 90