Javascript Course

PHP code is executed on the server side and output data are transmitted to Web browser.
JavaScript script code is executed by the browser on user's computer.
Combining these two web programming languages, JavaScript scripts can achieve dynamic results based on data received and processed by the server. Thus, the same web page can contain a JavaScript code for a user and other JS code for another user.

- There are two ways to combine PHP with JavaScript to achieve a dynamic and personalized result:

      1) By writing the entire JS script within PHP code and adding it to the web page with PHP function "echo" (or "print").
 // JS code ... ';
- The string returned by 'echo' must be a JS code with correct syntax.

      2) By adding in the JS script within the HTML document only the necessary data processed by PHP.

• Both versions must be written into .php files that can be processed by the PHP module.

1. Alert window with the user name

In a web site with authentication system to be displayed an alert window with the user name, after he logged in.
In this case we assume that the username is stored in a session variable ($_SESSION['name']).
Using the first method, would be the following PHP code:
alert("Welcome '. $_SESSION['nume']. '");';

Or the second way:


2. Clock with server time

A clock made with JavaScript and added in a web page will display the visitor's computer time. If you want to display the same time for all visitors, you can add and use the server time in the JS script, as it is in the following example:
- Test it yourself, in a .php file, on the server.