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
-
include the html as output by your script - I suspect you just have something missing from it.Paul Dixon– Paul Dixon2009年07月09日 16:00:17 +00:00Commented Jul 9, 2009 at 16:00
-
@Paul, why did you add the SCRIPT tags? Are you sure he makes use of them?Ionuț G. Stan– Ionuț G. Stan2009年07月09日 16:02:13 +00:00Commented Jul 9, 2009 at 16:02
-
Looks like some overlapping editsPaul Dixon– Paul Dixon2009年07月09日 16:04:07 +00:00Commented Jul 9, 2009 at 16:04
-
Paul, you're right. The original had SCRIPT tags, I had to click "view source" to see them.Ionuț G. Stan– Ionuț G. Stan2009年07月09日 16:05:36 +00:00Commented Jul 9, 2009 at 16:05
-
The script is not being called. i tried echo '<script type="text/javascript">alert("hello");testing();</script>'; and no alert came.Zeeshan Rang– Zeeshan Rang2009年07月09日 16:32:02 +00:00Commented Jul 9, 2009 at 16:32
3 Answers 3
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.
2 Comments
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
1 Comment
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.