Reputation: 14624
is it possible to run some javascript expression? for example echo eval("Math.sqrt('25')");
Upvotes: 5
Views: 20337
Reputation: 43
if you have node installed on your server then you can exec this command with php
node a.js
and then use the console.log as output.
Upvotes: 0
Reputation: 1
Run JavaScript code from PHP
php v8js: https://github.com/phpv8/v8js
$v8 = new V8Js;
$v8->executeString("Math.sqrt('25')"); // 5
https://github.com/chenos/execjs
use Chenos\ExecJs\Context;
$cxt = new Context;
$cxt->eval("Math.sqrt('25')"); // 5
Upvotes: 0
Reputation: 401182
In normal situations :
So, no, it's not quite possible to have PHP execute some Javascript code on the server.
But there is at least on PHP extension that embed (or wrap arround) a Javascript engine, and, as a consequence, allows one to execute Javascript on the server, from PHP.
The extension I'm thinking about is the spidermonkey one : installing and enabling it on your server will allow you to execute Javascript code, on the server, from PHP.
Of course, like any other PHP extension, you'll need to be admin of your server, in order to install it -- and this one is never installed by default, as it answers a very specific need.
About this extension, I have never seen it used in real situations, and there are not many people who tried it... here are two articles you might want to read :
Upvotes: 7
Reputation: 41
put your php into a hidden div and than call it with javascript
html / php part
<div id="mybox" style="visibility:hidden;"> echo sqrt(25); </div>
javascript part
var myfield = document.getElementById("mybox");
myfield.visibility = 'visible';
now, you can do anything with myfield... like this
alert(myfield);
Upvotes: 3
Reputation: 1566
There is also the J4P5
I don't know if it's still maintained but you can always fork it, it's released under the GPL license.
Upvotes: 3
Reputation: 578
Since PHP is a server-side scripting language that runs on the server and Javascript is a client-side scripting language that runs in a browser you would have to have the PHP generate Javascript code (the same way it generates HTML) that gets executed after the page is loaded.
Upvotes: 1
Reputation: 10594
Try this
echo "<script language='javascript'> Math.sqrt('25') </script>"
Upvotes: 5