Call JS Function

Running JavaScript inside PHP code

Join the DZone community and get the full member experience.

v8js is a new PHP extension able to run JavaScript code inside V8, Google’s JavaScript interpreter that powers for example Chrome and NodeJS.

This extension is highly alpha — and its API would probably change in the months ahead. Since documentation is lacking, I invite you to repeat the discovering process I follow in this post in case you find some differences in a new version of v8js.

Installation

V8 must be present on the machine in order to install the extension. On a Debian/Ubuntu system, run the following:

sudo apt-get install libv8-dev libv8-dbg

libv8-dev will also install libv8 in its latest version.

Afterwards, download and compile the extension with:

There are no more requirements for compilation apart from the usual dependencies for PECL packages, like build-essential.

to php.ini or to a section in conf.d.

will confirm you the extension is loaded.

Some introspection

PHP’s reflection let us take a look at the classes and methods provided by this extension, even without documentation available. It probably hasn’t been written yet, due to the unstable API.

$ php -r 'var_dump(get_declared_classes());' | grep V8 string(8) "V8Object" string(10) "V8Function" string(4) "V8Js" string(13) "V8JsException" $ php -r '$class = new ReflectionClass("V8Js"); var_dump($class->getMethods());' array(5) < [0]=>&object(ReflectionMethod)#2 (2) < ["name"]=>string(11) "__construct" ["class"]=> string(4) "V8Js" > [1]=> &object(ReflectionMethod)#3 (2) < ["name"]=>string(13) "executeString" ["class"]=> string(4) "V8Js" > [2]=> &object(ReflectionMethod)#4 (2) < ["name"]=>string(19) "getPendingException" ["class"]=> string(4) "V8Js" > [3]=> &object(ReflectionMethod)#5 (2) < ["name"]=>string(17) "registerExtension" ["class"]=> string(4) "V8Js" > [4]=> &object(ReflectionMethod)#6 (2) < ["name"]=>string(13) "getExtensions" ["class"]=> string(4) "V8Js" > > $ php -r '$v8 = new V8Js(); var_dump($v8->executeString("1+2+3"));' int(6)

Interesting! We have just executed our first JavaScript expression inside a PHP process. Apparently the last statement’s value is returned by the executeString() method, with a rough conversion preserving the type:

$ php -r '$v8 = new V8Js(); var_dump($v8->executeString("var obj = <>; obj.field = 1; obj.field++; obj.field;"));' int(2)

Syntax or runtime errors are signaled with a V8JsException:

$ php -r '$v8 = new V8Js(); var_dump($v8->executeString("var obj = <"));' PHP Fatal error: Uncaught exception 'V8JsException' with message 'V8Js::executeString():1: SyntaxError: Unexpected end of input' in Command line code:1 Stack trace: #0 Command line code(1): V8Js->executeString('var obj = <') #1 
thrown in Command line code on line 1

Let’s add more difficulty

The FizzBuzz kata OO solution is an example of JavaScript code creating an object and executing anonymous functions: it’s a good test bench for our integration.Since evaluating a variable as the last line returns it, that is our channel of communication, supporting integers, strings, floats, booleans, arrays (not objects at this time). Meanwhile, input for JavaScript code can be embedded into the executed string.

This code will output string(8) «FizzBuzz»:

 > if (result) < return result; >else < return number; >> > var myFizzBuzz = new FizzBuzz(); myFizzBuzz.accept(15); '; $v8 = new V8Js(); var_dump($v8->executeString($javaScriptCode));

By changing it a bit, we can build a JSON string by backslashing the double quotes («), and returns it in lieu of an object to communicate to the PHP process a complex result:

. var myFizzBuzz = new FizzBuzz(); ""; '; $v8 = new V8Js(); $result = $v8->executeString($javaScriptCode); var_dump($result); var_dump(json_decode($result));
string(33) "" object(stdClass)#2 (2) < ["15"]=>string(8) "FizzBuzz" ["5"]=> string(4) "Buzz" >

Wiring

Executing an external script would be nice: it would provide better stack traces, with traceable line numbers at the JavaScript level. It would also mean we won’t need backslashing for single quotes, simplifying the syntax.

We cannot load scripts on the JavaScript side out of the box, due to V8 missing this functionality (Node JS adds this feature) but we can load the code on the PHP Side:

// test.js $ php loadingfiles.php string(24) "test.js file was loaded." // loadingfiles.php executeString($javascriptCode); var_dump($result);
$ php loadingfiles.php string(24) "test.js file was loaded."

However, we still miss the capability of including JavaScript libraries.

Conclusion

There are many possible use cases for v8js, like sandboxed scripting or the integration of some code which was written for the client side. That would not be the most clean solution, but it’s a Turing complete approach, so why not?

After all, it’s already possible to run PHP on Java or Python and Ruby on .NET. JavaScript is becoming ubiquitous, so why not providing support for it, even in a caged box?

Opinions expressed by DZone contributors are their own.

Источник

Как написать js в php файле?

Пробую вот такой способ, но выдает ошибку. Как подключить правильно?

 $(document).mouseup(function () < $('.header__burger').click(function (e) < e.preventDefault() $('.header__nav').toggleClass('header__nav--active') >) >) $(document).mouseup(function (e) < var $target = $(e.target) if ($target.closest('.header__menu').length == 0) < $('.header__nav').removeClass('header__nav--active') >>) " ?>

sslion

615c8d31847e5263399964.png

кавычки здесь поставь одинарные

Raxen

Команда echo не запускает скрипты, она выводит текстом все что в нее всунуто.
Т.е. максимум, при исправлении ошибок синтаксиса, в вашем примере вы получите код js написанный в виде текста, например на странице или в консоли или где вы запускаете этот php, для того, чтоб код сработал, вам нужно выйти за рамки php , например —

   

И открыть на сервере. Не знаю где вы такому бреду нахватались, но теперь понимаю уровень персонала X5)

Raxen

JeorgeLaght, я пропущу оскорбления, но с чего вы взяли, что я путаю echo и print?

P.S. Бред — считать, что фронтендеры в Х5 пишут на PHP)

Источник

How to Call a JavaScript Function from PHP?

PHP is a server-side programming language which means it executes at the server end and it will return the HTML code. On the other hand, Javascript is client-side (runs at client browser) scripting language, which is used normally to validate clients details.

Example 1: Call Javascript function declared in the head section

In this example we are calling Javascript function “jsFunction” which is declared in the head section.

     '; ?> 

How to call a JavaScript function from 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. See example 2.

Example2: Execute javascript code through PHP

     alert("Execute Javascript Code"); '; ?> 

How to call a JavaScript function from PHP

  • Learn PHP Language
  • PHP Interview Questions and Answers
  • PHP Training Tutorials for Beginners
  • Display Pdf/Word Document in Browser Using PHP
  • Call PHP Function from JavaScript
  • Call a JavaScript Function from PHP
  • PHP Pagination
  • Alert Box in PHP
  • Php Count Function
  • PHP Filter_var ()
  • PHP array_push Function
  • strpos in PHP
  • PHP in_array Function
  • PHP strtotime() function
  • PHP array_merge() Function
  • explode() in PHP
  • implode() in PHP
  • PHP array_map()

Источник

Call JavaScript Function in PHP

Call JavaScript Function in PHP

In this article, we will introduce a method to call JavaScript function from PHP. We actually cannot call JavaScript function using PHP as these two languages do not understand each other. The only possible option is outputting the JavaScript function call in PHP. However, we also can write JavaScript in a PHP file and call the function.

Use the echo Function to Display the JavaScript Function Call in PHP

JavaScript is a client-side scripting language, while PHP is a server-side language. Technically, we cannot invoke JavaScript functions from PHP. But we can display the JavaScript using the echo function. This method includes the JavaScript function call in the output rather than the JavaScript function in PHP. We will define a JavaScript function first and then call the function. We can wrap the JavaScript invocation of the function with the echo function in PHP. Here, most work will be done by JavaScript, which is the function declaration and invocation. We will use PHP only to display the function invocation.

For example, create a PHP file index.php and inside the script tag write a JavaScript function showMessage() . Write the alert() function inside the showMessage() function. Write the text click here in the alert() function. Then, somewhere in the code, open the PHP tag and write the script tag and call the showMessage() function inside the tag. Then, wrap the script tag with the echo function.

We can also separate each element in the invocation by a single quote. The example is shown below.

When we run the script, then an alert message will pop up saying click here . We treated the JavaScript function as a string and used it to display with the echo function. It should be noted that the function should be declared before the invocation. Thus, we called the JavaScript function in PHP using the echo function.

function showMessage()  alert("click here"); > 

Источник

Читайте также:  Python command line application
Оцените статью