How do I use PHP to supply info to JavaScript?

649

I have a simple image-looping script that changes thesrc of an image.

function cycleNext()
{
    ++imgIndex;

    if(imgIndex>imgCount)
    {
        imgIndex = 1;
    }

    setImgSrc(imgIndex);
}

However, at present, I'm (shudder) manually enteringimgCount in my script. The alternative is server-side, but I don't know how to fetch this information. I imagine it's pretty simple, though.

How can I use PHP to supply this script with the number of images in the folder?

442

Answer

Solution:

<?php
$directory = "Your directory";
$filecount = count(glob("" . $directory . "*.jpg"));
$filecount += count(glob("" . $directory . "*.png"));
?>

Repeat the 2nd line for each extension you wish to count.

function cycleNext()
{
    ++imgIndex;

    if (imgIndex > <?php echo $filecount;?>)
    {
        imgIndex = 1;
    }

    setImgSrc(imgIndex);
}

That should do it.

EDIT:

function cycleNext(imgCount)
{
    ++imgIndex;

    if (imgIndex > imgCount)
    {
        imgIndex = 1;
    }

    setImgSrc(imgIndex);
}

Then when you call cycleNext, call it with the variable.

cycleNext(<?php echo $filecount; ?>);
450

Answer

Solution:

if the .js file is a separate file. then you can do this:

change the.js for a.php

then you can add<?php ?> tags just like you do in your.php files.

just don't forget to add the header in the code, indicating that the file is a javascript file. like that:

<?php header("Content-type: text/javascript"); ?>

and you will call the file with it's actual namesrc="file.php"

251

Answer

Solution:

You can do it in three ways:

  1. Making your .js file a .php file (with the correct mime-type) and just use an echo in that .js.php-file
  2. include the javascript to the <head> tag of your page
  3. echo a variable into a <script> tag in your <head> and use it in your javascript file. Example:

    <script type="text/javascript">
      var imgCount = <?php echo $imagecount ?>
    </script>;
    
627

Answer

Solution:

During the generation of the HTML code, simply insert a<script> line, for instance

  echo '<script type="text/javascript">';
  echo 'var imgCount=' . $NumberOfImages . ';';
  echo '</script>';

Just ensure that line is provided beforecycleNext() is called (or imgCount is used).

People are also looking for solutions to the problem: json - PHP 7.1 json_decode() undefined

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.