Php javascript on load

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.

Источник

Php calling javascript on load

For example: I have this php code, loading page in this case takes ~5 sec, and i want to event on start page loading and on the end of loading. and Javascript function is simple Thanks in advance Solution: Instead of calling the function in , you need to wrap the call in a function that gets assigned by reference to .

Php calling javascript on load

Guys i have little problem with PHP to call Javascript function on load . Idea is when page load i do little calculation with PHP stuff , so when i finish that all i want is to write that down in same DOM element using javascript. I will not show you PHP code for calculation as i am 100% sure it is alright. This is the code i got so far , so can you just tell me whats wrong with it?

$test = 100; echo "  "; 

and Javascript function is simple

function UpdatePoints(Points)

Instead of calling the function UpdatePoints() in window.onload , you need to wrap the call in a function that gets assigned by reference to window.onload . Otherwise, you are calling the function, and assigning its return value to window.onload .

// This function wraps UpdatePoints($test) // and is assigned as a reference to window.onload function load() < UpdatePoints(); > echo "  "; 

Note that the language attribute to the tag is deprecated. Include a type=text/javascript attribute in its place (though text/javascript is genearlly the browser default)

However, since the value of $test is created before the page loads and cannot change when the function is called, you might as well not bother passing it as a parameter, in which case you don’t need to wrap the function. Just remove the () to assign it as a reference.

echo "  "; function UpdatePoints() < // PHP write directly into the function since the value // can't change. It's always going to be passed as what PHP assigns // if you call it as UpdatePoints($test) var Points = $test; document.getElementById('PointsNumber').innerHTML = Points; >

Page Loading Query, script type=»text/javascript»> ; // unblock when ajax activity stops $(document).ajaxStop($.unblockUI); function test() < $.ajax(< url: 'wait.php

Php + jquery event on starting page loading

Is it possible to get event on starting page loading, when DOM structure isnt complete?

I have this php code, loading page in this case takes ~5 sec, and i want to event on start page loading and on the end of loading.

Event when site is ready i can get with

but on starting loading? Can someone help with it?

Just write inline javascript at the start of your page, and before these PHP codes. The browser will execute inline JS as it reads it.

However, that won’t work in your example, because in your example, it’s not the page load that takes the time, it’s the server-side page generation.

You’d have to use php’s flush() to flush the output buffer and push the javascript to the browser before actually doing the work.

Passing Variables OnLoad using PHP $_GET[»] With Ajax, So I have an HTML, PHP and ajax application that is loading this page: ViewOrderReports.php?order_number=77409362. I am trying to pass the

Button onclick event triggered on every page load

I have a button which has a onclick attribute which calls a function. My problem is that whenever the page loads it automatically triggers the onclick event without me clicking on anything.

I’ve tried different variatons of syntax but nothing worked. I swapped ‘button’ for ‘input type=button’ but that didn’t help anything.

$sql = "SELECT books.id, books.name as bookname, authors.name as authorname, autori.surname, genre, description, stock FROM books JOIN authors ON books.author_id=authors.id ORDER BY books.name ASC"; $result = $conn->query($sql); if ($result->num_rows > 0) < echo "Name of the bookAuthorCopies available"; while($row = $result->fetch_assoc()) < echo "".$row["bookname"]."".$row["authorname"]." ".$row["surname"]."".$row["stock"].""; if (isAvailable($row["id"]) && isset($_SESSION["id"])) < ?>"> 

and I’m calling the function borrowBook from functions.php which looks like this.

function borrowBook($idbook) < $servername = "aaa"; $username = "bbb"; $password = "ccc"; $dbname = 'ddd'; $iduser = $_SESSION["id"]; $conn = new mysqli($servername, $username, $password, $dbname); if ($conn->connect_error) < die("Connection failed: " . $conn->connect_error); > $sql = "UPDATE books SET stock = stock - 1 where . $idbook; $conn->query($sql); $sql = "INSERT INTO reservations(id, dateBorrowed, dateReturn, returned, kniha_id, uzivatel_id) VALUES (NULL, NOW(), DATE_ADD(NOW(), INTERVAL 34 DAY), 0, $idbook, $iduser)"; $conn->query($sql); > 

So the SQL query and everything actually works. When I check the database I actually get new entries and everything is as expected. The only problem I’m having is that the button’s onclick event is always triggered on every page load and I can’t seem to fix it. From searching online everybody is using stuff like JavaScript or jQuery so it didn’t really help me.

Hi and welcome to Stack Overflow!

Looks like you are trying to call php function from the client (browser). This is however impossible.

The way the PHP works is, that it prepares the content for the client and sends it to the client. After it is send, you cannot interact with the PHP code anymore. What you need to do is make client send another request.

My problem is that whenever the page loads it automatically triggers the onclick event without me clicking on anything.

You need to change the infrastructure a bit. For the beginning i’d suggest not using JS at all, but instead create second PHP page, that just does the borrowBook using GET parameter (you can expand it later) (See PHP’s $_GET)

First you need to actually create the second page (let’s call it borrowBook.php ) This page will get book’s id using GET parameter (let’s call that bookid )

This page’s code may look something like this (Note: code is not tested)

And now you need to change original code’s line

What this does is, that PHP sees section with value of $row[«id»] . Which if id is 1 will result in this:

You should use js (or jquery) in onclick handler that call your php-script with ajax. PHP scripts works only in server. Like this (jquery example):

 

And in myscript.php call your function.

Onload Event, The onload event can be used to check the visitor’s browser type and browser version, and load the proper version of the web page based on the information.

Running code in Javascript to make a PHP and HTML file run from an ONLOAD event

As a newbie I am trying to run a PHP file and then an HTML file automatically using an onload=»Trigger();» in the body of the HTML.

Enclosed is my code but it will not work even though the onload is accessing the Javascript code.

It looks like you need to submit two forms onLoad. In your HTML create two forms, but the issue is that you are targeting the same frame, so while one is submitting the other is trying to as well (you could time it so one submits, the other waits until it is submitted OR target another frame like so:

OR a timed method so one submits then the other shortly after using the same target:

    function trigger()< document.php-form.submit(); setTimeout(function()< document.htm-form.submit(); >, 2000); // 2 seconds after > 

How to add onload() event into @section(‘content’) of laravel, The advantage of this method is that it will only be called after the entire page being loaded, so the order of the

Источник

Читайте также:  Css выравнивание контента центру
Оцените статью