How do I use PHP to supply info to JavaScript?
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?
Answer
Solution:
Repeat the 2nd line for each extension you wish to count.
That should do it.
EDIT:
Then when you call cycleNext, call it with the variable.
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:
and you will call the file with it's actual name
src="file.php"
Answer
Solution:
You can do it in three ways:
echo a variable into a <script> tag in your <head> and use it in your javascript file. Example:
Answer
Solution:
During the generation of the HTML code, simply insert a
<script>
line, for instanceJust ensure that line is provided before
cycleNext()
is called (or imgCount is used).