Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php run javascript code

Tags:

javascript

php

is it possible to run some javascript expression? for example echo eval("Math.sqrt('25')");

like image 707
kusanagi Avatar asked Feb 25 '11 19:02

kusanagi


People also ask

Can I run JavaScript in PHP?

You can execute Javascript through PHP by calling javascript code/function as a string in PHP and send it to the client browser to execute.

How run js file in PHP?

You need to include the JavaScript file in the markup and then specify a function from it to be executed on click of the input. Show activity on this post. PHP is a server-side language and you can not call JavaScript from it. Because javascript is a client-side language and actually the browser runs it.

How call JavaScript function in PHP if condition?

php if ($value == 1) { echo '<script type="text/javascript">'; echo '$(document). ready(function(){ /* do_something_in_javascript */ });'; echo '</script>'; } ?>

Can PHP interact with JavaScript?

Answer : PHP and Javascript cannot directly interact since PHP is a server side language and Javascript is a client-side language. However, we can exchange variables since PHP can generate Javascript code to be executed by the browser and it is possible to pass specific variables back to PHP via the URL.


1 Answers

In normal situations :

  • PHP runs on the server
  • and, then, Javascript is run on the client, in the browser.

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 :

  • Using JavaScript in PHP with PECL and SpiderMonkey
  • and SpiderMonkey : Exécuter du Javascript côté serveur, depuis PHP (this one is in french, and on my own blog)
like image 80
Pascal MARTIN Avatar answered Oct 18 '22 10:10

Pascal MARTIN