How to call a JavaScript function from PHP?

PhpJavascript

Php Problem Overview


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.

Php Solutions


Solution 1 - Php

As far as PHP is concerned (or really, a web server in general), an HTML page is nothing more complicated than a big string.

All the fancy work you can do with language like PHP - reading from databases and web services and all that - the ultimate end goal is the exact same basic principle: generate a string of HTML*.

Your big HTML string doesn't become anything more special than that until it's loaded by a web browser. Once a browser loads the page, then all the other magic happens - layout, box model stuff, DOM generation, and many other things, including JavaScript execution.

So, you don't "call JavaScript from PHP", you "include a JavaScript function call in your output".

There are many ways to do this, but here are a couple.

Using just PHP:

echo '<script type="text/javascript">',
     'jsfunction();',
     '</script>'
;

Escaping from php mode to direct output mode:

<?php
    // some php stuff
?>
<script type="text/javascript">
    jsFunction();
</script>

You don't need to return a function name or anything like that. First of all, stop writing AJAX requests by hand. You're only making it hard on yourself. Get jQuery or one of the other excellent frameworks out there.

Secondly, understand that you already are going to be executing javascript code once the response is received from the AJAX call.

Here's an example of what I think you're doing with jQuery's AJAX

$.get(
    'wait.php',
    {},
    function(returnedData) {
        document.getElementById("txt").innerHTML = returnedData;

        //  Ok, here's where you can call another function
        someOtherFunctionYouWantToCall();

        // But unless you really need to, you don't have to
        // We're already in the middle of a function execution
        // right here, so you might as well put your code here
    },
    'text'
);

function someOtherFunctionYouWantToCall() {
    // stuff
}

Now, if you're dead-set on sending a function name from PHP back to the AJAX call, you can do that too.

$.get(
    'wait.php',
    {},
    function(returnedData) {
        // Assumes returnedData has a javascript function name
        window[returnedData]();
    },
    'text'
);

* Or JSON or XML etc.

Solution 2 - Php

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

Solution 3 - Php

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);
}

?>

Solution 4 - Php

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

Solution 5 - Php

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: https://stackoverflow.com/questions/9023790/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

Solution 6 - Php

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\"";
?>

Solution 7 - Php

try like this

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

Solution 8 - Php

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>

Solution 9 - Php

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>';
}

Solution 10 - Php

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

Solution 11 - Php

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!

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionZeeshan RangView Question on Stackoverflow
Solution 1 - PhpPeter BaileyView Answer on Stackoverflow
Solution 2 - PhpGStoView Answer on Stackoverflow
Solution 3 - PhpbertzzieView Answer on Stackoverflow
Solution 4 - PhpMatthew FlaschenView Answer on Stackoverflow
Solution 5 - PhpPian0_M4nView Answer on Stackoverflow
Solution 6 - PhpDaffView Answer on Stackoverflow
Solution 7 - PhpVivek abView Answer on Stackoverflow
Solution 8 - PhpumeshView Answer on Stackoverflow
Solution 9 - PhpRick JamesView Answer on Stackoverflow
Solution 10 - PhpDaniel MouraView Answer on Stackoverflow
Solution 11 - PhpHamman SamuelView Answer on Stackoverflow