Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript inside PHP not working (document.getElementById)

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.

like image 659
Albert Renshaw Avatar asked Nov 07 '12 02:11

Albert Renshaw


2 Answers

<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>"; ?>
like image 163
Ruben-J Avatar answered Sep 21 '22 17:09

Ruben-J


<iframe id='id' onload='display();' name='my_id' src='www.test.com'></iframe>   

<script type='text/javascript'>
function display(){
    alert('Loading');
}
</script>
like image 45
Manish Avatar answered Sep 21 '22 17:09

Manish