tags:

views:

163

answers:

3

I am using my php to call a js function like this:

<?php 
$chk=1;
if($chk==1)
{
    echo '<script>testing();</script>';
}
?>

and my js looks like:

function testing()
{
   document.getElementById("mainbody").innerHTML="This is my first JavaScript!";
}

The js is an external js file.

My html looks like:

<html>
<head>
<script src="qotw.js"></script>
</head> 
    <body>
    <div id="mainbody"></div>     
    </body>
</html>

but this is not working. What am i doing wrong over here? Please tell me if you know.

Best Zeeshan

+7  A: 

You run the script before the div you are targeting exists, so the document.getElementById call returns a false value instead of an HTMLElementNode.

You either need to move the script element so it is after the div, or assign the function to an event handler (onload for instance) instead of calling it directly.

This has nothing to do with the use of PHP.

Incidentally, your HTML is invalid and triggers quirks mode.

David Dorward
No that is not happening. The div id=mainbody has a button inside it, onclick=the js is called and from that js further php is called.
Zeeshan Rang
You can't call PHP from JS. PHP runs on the server, generates a document (containing JS), delivers it to the client, the client then runs the JS. It is too late for any more PHP to run at this point - a new HTTP request has to be made to the server. You appear to have reduced your test case too far and deleted some of the information needed to see all your errors.
David Dorward
+1  A: 

Make sure that 'testing' isn't called above 'mainbody' in the code, because then the code would be run at a point during load, when the object doesn't exist.

David Hedlund
+1  A: 

Try testing the following in order:
first: Your script is being called

<script type="text/javascript">alert("hello");testing();</script>

second: The function is being called

function testing() {
    alert('inside testing');
}

third: As suggested above,

if (document.getElementById("mainbody") == null) alert('yep, its null');

then let us know the results

David Archer
The script is not being called. i tried echo '<script type="text/javascript">alert("hello");testing();</script>';and no alert came.
Zeeshan Rang
but if i try the echo "show result"; it works.
Zeeshan Rang