JavaScript inside PHP not working (document.getElementById)

Albert Renshaw picture Albert Renshaw · Nov 7, 2012 · Viewed 10.7k times · Source

Something weird is happening but I can't seem to get the JavaScript code document.getElementById working inside of PHP...

For example, load the following PHP code (below) into a PHP file and run it, there is no JavaScript alert? But if you copy the source-code that the PHP echoed (or printed) and run it as an HTML file there is a JavaScript alert? So any element that is created inside of PHP tags doesn't run in JavaScript, even if the JavaScript is kept outside of the PHP tags?

Here is the PHP demo code:

<?php 
print "
<iframe id='my_id' name='my_id' src='http://www.php.com/'></iframe>

<SCRIPT LANGUAGE='javascript'> 
document.getElementById('my_id').contentWindow.onload = function(){
    alert('content loaded');
}
</SCRIPT>
";
?>

It even doesn't work if just this is your code:

<iframe id='my_id' name='my_id' src='<?php echo"http://www.php.com/"; ?>'></iframe>

<SCRIPT LANGUAGE='javascript'> 
document.getElementById('my_id').contentWindow.onload = function(){
    alert('content loaded');
}
</SCRIPT>

Here is the source code that appears (upon request) (Also the contentWindow.onLoad is working fine for content that is not on the same domain as mine in Safari):

<iframe id='my_id' name='my_id' src='http://www.php.com/'></iframe>

<SCRIPT LANGUAGE='javascript'> 
document.getElementById('my_id').contentWindow.onload = function(){
    alert('content loaded');
}
</SCRIPT>

My issue is that in HTML this code works fine and the alert is called.... in PHP the code does not work and the alert is never called... There is something wrong with the way PHP handles document.getElementById, there is nothing wrong with .contentWindow.onload.

Answer

Ruben-J picture Ruben-J · Nov 9, 2012
<iframe id='my_id' onload="alert('Content Loaded');" name='my_id' src='http://www.php.com/'></iframe>

Or better

<iframe id='my_id' onload='ShowAlert();' name='my_id' src='http://www.php.com/'></iframe>   

<script type='text/javascript'>
function ShowAlert(){
    alert('Content Loaded');
}
</script>

Or if you want to echo it

<?php
echo "<iframe id='my_id' onload='ShowAlert();' name='my_id' src='http://www.php.com/'></iframe>   

<script type='text/javascript'>
function ShowAlert(){
    alert('Content Loaded');
}
</script>"; ?>