Auz Beauxdine Auz Beauxdine - 1 month ago 6
Javascript Question

PHP echo'ing JavaScript will not work

I've been trying to use PHP to output some JavaScript in a reload image script, but I can't get it to work.

The original code is:

<script type="text/javascript">
function reloadImage() {
var myDate = new Date();

<?php
$len = count($_POST['custom_wall']);
for ($x = 0; $x < $len; $x++) {
$imgNum = $x + 1;
$jstxt1 = 'img' . $imgNum . '.src = \'http://' . $resultExplode[0] . '/jpeg?t=\' + myDate.getTIme();' . PHP_EOL;
echo $jstxt1;
}
echo '}' . PHP_EOL;

echo 'if (document.getElementByID) {' . PHP_EOL;
for ($y = 0; $y < $len; $y++) {
$imgNum2 = $y + 1;
$jstxt2 = 'var img' . $imgNum2 . ' = document.getElementByID(\'Cam' . $imgNum2 . '\');' . PHP_EOL;
echo $jstxt2;
}

?>
window.setInterval('reloadImage()', 1000);

}
</script>


When I run the page, it renders the correct output (see below) but doesn't reload the images.

<script type="text/javascript">
function reloadImage() {
var myDate = new Date();
img1.src = 'http://172.16.140.56/jpeg?t=' + myDate.getTIme();
img2.src = 'http://172.16.140.56/jpeg?t=' + myDate.getTIme();
img3.src = 'http://172.16.140.56/jpeg?t=' + myDate.getTIme();
}
if (document.getElementByID) {
var img1 = document.getElementByID('Cam1');
var img2 = document.getElementByID('Cam2');
var img3 = document.getElementByID('Cam3');
window.setInterval('reloadImage()' , 1000);
}
</script>


BUT, if I don't use PHP, and just insert the JS exactly as it is outputted, the script will work correctly.

I tried echoing the entire script in PHP, thinking that maybe the order it was interpreting was an issue, but no luck. I also wondered if it had to do with using the end-of-line function.

Any ideas? Thanks.

Answer

Your if condition:

if (document.getElementByID) {

will always be false, because document.getElementByID is undefined. JS is case sensitive; change the D on the end to a lowercase d:

if (document.getElementById) {

Or just remove the if test entirely, because all browsers support document.getElementById so there's no need to test for it.

You will also need to make the same change to the lines inside the if.

(Finally, the script element would need to be included on the page somewhere after the elements it tries to manipulate - just before the closing </body> tag is a common place to put script elements.)

Comments