[php] How to call a JavaScript function from PHP?

How to call a JavaScript function from PHP?

<?php

  jsfunction();
  // or
  echo(jsfunction());
  // or
  // Anything else?

The following code is from xyz.html (on a button click) it calls a wait() in an external xyz.js. This wait() calls wait.php.

function wait() 
{
  xmlhttp=GetXmlHttpObject();
  var url="wait.php"; \
  xmlhttp.onreadystatechange=statechanged; 
  xmlhttp.open("GET", url, true); 
  xmlhttp.send(null);
} 

function statechanged()
{ 
  if(xmlhttp.readyState==4) {
       document.getElementById("txt").innerHTML=xmlhttp.responseText;
  }
}

and wait.php

<?php echo "<script> loadxml(); </script>"; 

where loadxml() calls code from another PHP file the same way.

The loadxml() is working fine otherwise, but it is not being called the way I want it.

This question is related to php javascript

The answer is


I don't accept the naysayers' answers.

If you find some special package that makes it work, then you can do it yourself! So, I don't buy those answers.

onClick is a kludge that involves the end-user, hence not acceptable.

@umesh came close, but it was not a standalone program. Here is such (adapted from his Answer):

<script type="text/javascript">
function JSFunction() {
    alert('In test Function');   // This demonstrates that the function was called
}
</script>

<?php
// Call a JS function "from" php

if (true) {   // This if() is to point out that you might
              // want to call JSFunction conditionally
    // An echo like this is how you implant the 'call' in a way
    // that it will be invoked in the client.
    echo '<script type="text/javascript">
         JSFunction();
    </script>';
}

You may not be able to directly do this, but the Xajax library is pretty close to what you want. I will demonstrate with an example. Here's a button on a webpage:

<button onclick="xajax_addCity();">Add New City</button> 

Our intuitive guess would be that xajax_addCity() is a Javascript function, right? Well, right and wrong. The cool thing Xajax allows is that we don't have any JS function called xajax_addCity(), but what we do have is a PHP function called addCity() that can do whatever PHP does!

<?php function addCity() { echo "Wow!"; } ?>

Think about it for a minute. We are virtually invoking a PHP function from Javascript code! That over-simplified example was just to whet the appetite, a better explanation is on the Xajax site, have fun!


If you want to echo it out for later execution it's ok

If you want to execute the JS and use the results in PHP use V8JS

V8Js::registerExtension('say_hi', 'print("hey from extension! "); var said_hi=true;', array(), true);
$v8 = new V8Js();
$v8->executeString('print("hello from regular code!")', 'test.php');
$v8->executeString('if (said_hi) { print(" extension already said hi"); }');

You can refer here for further reference: What are Extensions in php v8js?

If you want to execute HTML&JS and use the output in PHP http://htmlunit.sourceforge.net/ is your solution


You can't. You can call a JS function from HTML outputted by PHP, but that's a whole 'nother thing.


Thats not possible. PHP is a Server side language and JavaScript client side and they don't really know a lot about each other. You would need a Server sided JavaScript Interpreter (like Aptanas Jaxer). Maybe what you actually want to do is to use an Ajax like Architecture (JavaScript function calls PHP script asynchronously and does something with the result).

<td onClick= loadxml()><i>Click for Details</i></td>

function loadxml()
{
    result = loadScriptWithAjax("/script.php?event=button_clicked");
    alert(result);
}

// script.php
<?php
    if($_GET['event'] == 'button_clicked')
        echo "\"You clicked a button\"";
?>

PHP runs in the server. JavaScript runs in the client. So php can't call a JavaScript function.


try like this

<?php
 if(your condition){
     echo "<script> window.onload = function() {
     yourJavascriptFunction(param1, param2);
 }; </script>";
?>

I always just use echo "<script> function(); </script>"; or something similar. you're not technically calling the function in PHP, but this as close as your going to get.


Per now (February 2012) there's a new feature for this. Check here

Code sample (taken from the web):

<?php

$v8 = new V8Js();

/* basic.js */
$JS = <<< EOT
len = print('Hello' + ' ' + 'World!' + "\\n");
len;
EOT;

try {
  var_dump($v8->executeString($JS, 'basic.js'));
} catch (V8JsException $e) {
  var_dump($e);
}

?>

you can try this one also:-

    public function PHPFunction()
    {
            echo '<script type="text/javascript">
                 test();
            </script>'; 
    }
    <script type="text/javascript">
    public function test()
    {
        alert('In test Function');
    }
    </script>