234

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.

Mithun Satheesh
  • 27,240
  • 14
  • 77
  • 101
Zeeshan Rang
  • 19,375
  • 28
  • 72
  • 100

12 Answers12

416

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.

3N1GM4
  • 3,372
  • 3
  • 19
  • 40
Peter Bailey
  • 105,256
  • 31
  • 182
  • 206
  • 2
    There's off course also the option of linking in an external javascript file that does the call itself... That way you keep JavaScript where it belongs, in the JavaScript code. =) – PatrikAkerstrand Jun 25 '09 at 19:54
  • this is not working. i tried both of them. the follow of my program is, from .html (on button click) it goes to an external .js function which load a php file (using xmlhttp=GetXmlHttpObject();var url="phpwithmysqlwait.php"; xmlhttp.onreadystatechange=statechanged; xmlhttp.open("GET", url, true); xmlhttp.send(null); ) and my php call loadxml(); "; ?> where loadxml calls another php the same way. The loadxml() is working fine otherwise, but it is not being called the way i want it. can you please suggest somthing – Zeeshan Rang Jun 25 '09 at 20:09
  • Update your original question with this info so that it's easier to read. I can modify my answer to address these specifics – Peter Bailey Jun 25 '09 at 20:22
  • Sadly I was expecting some fancy answer with websockets from the title until I saw the date... – Francisco Presencia Aug 11 '13 at 17:04
  • What about with getJSON? When I use getJSON and I send back a string of html with a script in it I usually incur an error of some sort (I can't remember it at this point). Any reason why that should happen? – Ty_ May 01 '14 at 14:12
  • 13
    This guy just made everything I've been doing up until now so clear. – Kacy Jan 04 '15 at 00:59
  • 4
    @PeterBailey Most people would usually insult the person for making this enquiry and leave it at that. You actually gave me really constructive help. so thank you :) – Gideon Sassoon Apr 05 '16 at 22:12
  • The using just PHP approach doesn't seem to work in my code: if the function has been declared in JS, it will not be available when the PHP gets parsed. Please correct me if I'm making a mistake here - is there a way to 'hold / pause' the PHP parser until the JS is ready? Oh, looking at the date, I'm a bit late to the party.... – Neil S3ntence Oct 09 '16 at 21:57
  • 2
    @NilsSens Thanks for your question. You still misunderstand something fundamental here. PHP and client-side javascript do not interact with eachother directly. HTTP is always in the middle. Even with Ajax requests that is the the case. To reiterate what I wrote now over 7 years ago in my original answer: when functioning as a web application server, all PHP is doing is generating a string of HTML, which may or may not include javascript. – Peter Bailey Oct 11 '16 at 14:00
  • Can we return of the output of `echo` into a variable in `PHP`? – alper Feb 19 '19 at 12:01
  • Exactly, and this is true not only for .html/.php files, but also for many other ones which uses xml language to store even complex project files (like Photoshop, PowerPoint, etc.) and all their inner data... letting the software itself to recreate visually all the stuff, when you open a project file. – Luca Lindholm Aug 24 '20 at 13:42
  • From PHP, I actually want to call a PHP or HTML program (perhaps via GET or POST) that executes JavaScript to produce some output, then return that output to the original PHP program synchronously, just like this question asks! This is so that server code can get and set local storage on the client. – David Spector Jun 14 '21 at 22:55
92

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.

soycharliente
  • 777
  • 2
  • 7
  • 26
GSto
  • 41,512
  • 37
  • 133
  • 184
59

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

?>
bertzzie
  • 3,558
  • 5
  • 30
  • 41
  • This may not fit the original question's use case exactly, but going by the question title this answer should have way more votes. – Chris Schmitz Feb 25 '15 at 14:58
  • 7
    Just be aware that this requires installing the V8Js extension to your PHP installation. – Velojet Apr 17 '16 at 02:32
11

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

Matthew Flaschen
  • 278,309
  • 50
  • 514
  • 539
  • 1
    well i am able to call a JS function like this:echo "Click for Details";.... but i dont want to click anything now. i just want my php to call a JS function with any event. – Zeeshan Rang Jun 25 '09 at 19:52
  • 2
    That example is using a click event in HTML, not php. JavaScript is client side and php is server side. You cannot directly call JavaScript with PHP. – MrChrister Jun 25 '09 at 19:57
10

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

Community
  • 1
  • 1
Pian0_M4n
  • 2,505
  • 31
  • 35
7

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\"";
?>
Daff
  • 43,734
  • 9
  • 106
  • 120
5

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

Ordering It is important that the function be declared "before" it is used. (I do not know whether "before" means 'lexically before' or 'temporally before'; in the example code above, it is both.)

Rick James
  • 135,179
  • 13
  • 127
  • 222
4

try like this

<?php
 if(your condition){
     echo "<script> window.onload = function() {
     yourJavascriptFunction(param1, param2);
 }; </script>";
?>
Vivek ab
  • 660
  • 6
  • 15
3

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>
tkanzakic
  • 5,499
  • 16
  • 34
  • 41
umesh
  • 39
  • 1
  • 1
    -1 as this won't work. You are calling and defining these hoisting functions in two separate blocks. Read [this](http://stackoverflow.com/questions/21807135/why-is-my-javascript-function-not-being-called-in-my-div) and [this](http://stackoverflow.com/questions/24438186/calling-javascript-function-from-php-not-working) – Siraj Alam Apr 05 '17 at 17:16
2

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

Daniel Moura
  • 7,816
  • 5
  • 35
  • 60
  • 14
    Strictly speaking, that's not true. There is also server-side JavaScript and you could theoretically have both PHP and JavaScript running on a server and calling each other. In practice, it's or course a very unlikely scenario. – Michael Borgwardt Jun 25 '09 at 20:24
1

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!

wdyp
  • 560
  • 4
  • 16
Hamman Samuel
  • 2,350
  • 4
  • 30
  • 41
0

For some backend node processing, you can run JS script via shell and return the result to PHP via console.log

  function executeNode($script)
  {
    return shell_exec('node -e \'eval(Buffer.from("'.base64_encode($script).'", "base64").toString())\'');
  }


  $jsCode = 'var a=1; var b=2; console.log(a+b);';
  
  echo executeNode($jsCode);
Adrian
  • 1