Javascript inside PHP not working (document.getElementById)

So 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”

Thankyou :)

Leave a Reply

*

Hire Me
Follow Me!
Search
Most Popular Articles & Pages
Because your vote is Important
Sorry, there are no polls available at the moment.
Categories