PDA

View Full Version : Adding PHP code to Javascrip



gary.mcgill
02-18-2014, 06:48 PM
I am using the fadeimages plugin and I want to be able to dynamically build the array instead of having it static. I have created a PHP file that builds the array by reading the contents of a pictures directory. My question is how to include this code into the javascript where the array would normally be. Here is the php file:

<?php // Build fadepic array
$x=0;
foreach (glob("../main_page_images/*.*") as $filename) {
$filename = substr($filename, 20);
echo "fadeimages[".$x."]=[\"main_page_images/".$filename."\", \"\", \"\"]<br>";
$x++; ?>

And of course I want to put it where the array would be. I have been trying to use json but can't get it to work properly. Any help would be greatly appreciated. Thanks!

Beverleyh
02-18-2014, 07:28 PM
If I'm understanding correctly, you could put the JavaScript internally in the web page and echo the PHP into it - very simply;


<html>
<head>

<script>
... script stuff ...

<?php // Build fadepic array
$x=0;
foreach (glob("../main_page_images/*.*") as $filename) {
$filename = substr($filename, 20);
echo "fadeimages[".$x."]=[\"main_page_images/".$filename."\", \"\", \"\"]<br>";
$x++; ?>

... more script stuff ...
</script>

</head>
<body>

... HTML stuff ...

</body>
</html>This will only work with the JavaScript located directly into the web page. It wouldn't work if the JavaScript is in an external file (js client-side / php server-side differences).

If you need more help, please provide a link to the script demo page here on DD and also a link to your page.

gary.mcgill
02-18-2014, 07:52 PM
I wish that worked... I must be overlooking something. You can see the test file at http://www.kimwatt.org/index_test.php. You will be able to see I have the php code embedded and the javascript is on the same page as you say. I know the php code works because you can run it alone by going to http://www.kimwatt.org/build_array.php and it outputs the array just as it is needed. you can see the actual array if you view the source on the site's index page. I am trying to get it so I can just drop .jpg files in a directory and the array builds dynamically. Thank you very much for your help!

gary.mcgill
02-18-2014, 08:13 PM
viewing the source I see now why it's not working. it is adding a /s after the / in the array. Here is a element it printed:
fadeimages[0]=["main_page_images/s/fade_pic_2.jpg", "", ""]
The /s should not be there. How can I get rid of it?

gary.mcgill
02-18-2014, 08:31 PM
I got it working!!! i had to put a \n to send a newline in the array. Also the /s is because I didnt have the substr set to the proper length. (its been a long day). Thanks for your help!