I am trying to call a javascript function from php. According to all of the examples I have been looking at the following should work but it doesn't. Why not?
<?php
echo "function test";
echo '<script type="text/javascript"> run(); </script>';
?>
<html>
<script type="text/javascript">
function run(){
alert("hello world");
}
</script>
</html>
-
2You must execute function after it was declared. In the above example you execute undefined function.Arkadiusz 'flies' Rzadkowolski– Arkadiusz 'flies' Rzadkowolski2012年10月10日 05:59:42 +00:00Commented Oct 10, 2012 at 5:59
-
But that doesn't make sense, I tested this but placing a run(); inside the javascript before the function was defined and it still called the function correctly.user1334130– user13341302012年10月10日 06:02:49 +00:00Commented Oct 10, 2012 at 6:02
-
It makes perfect sense. You can execute it in THE SAME "<script>" scope before function is declared, but not in the <script> tag that happens before second one pops in.Arkadiusz 'flies' Rzadkowolski– Arkadiusz 'flies' Rzadkowolski2012年10月10日 06:04:53 +00:00Commented Oct 10, 2012 at 6:04
3 Answers 3
Your html is invalid. You're missing some tags.
And you need to call the function after it has been declared, like this
<html>
<head>
<title></title>
<script type="text/javascript">
function run(){
alert("hello world");
}
<?php
echo "run();";
?>
</script>
</head>
<body>
</body>
</html>
In this case you can place the run before the method declaration, but as soon as you wrap the method call inside another script tag, the script tag has to be after the method declaration.
Try yourself http://jsfiddle.net/qdwXv/
Comments
the function must declare before use
it should be
<html>
<script type="text/javascript">
function run(){
alert("hello world");
}
<?php
echo "function test";
echo run(); ;
?>
</script>
</html>
Comments
As others have suggested, the function needs to be declared first. But, if you need to echo out the JavaScript from PHP first, you can either store it in a PHP variable to echo out later, or have your code wait for the dom to finish loading first...
document.ready = function() {
run()
}
If you're using jQuery or another framework, they probalby have a better way of doing that... In jQuery:
$(function(){
run();
})