Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

calling javascript function from php

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>
like image 575
user1334130 Avatar asked Oct 10 '12 05:10

user1334130


2 Answers

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/

like image 123
UpCat Avatar answered Sep 30 '22 19:09

UpCat


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>
like image 21
NullPoiиteя Avatar answered Sep 30 '22 18:09

NullPoiиteя