How to Turn Javascript Into PHP
JavaScript and PHP are two popular web design tools. Many people learn JavaScript first and then move on to PHP. They often ask how to turn their existing JavaScript into PHP. JavaScript and PHP, however, work in very different ways. PHP is the more powerful language, but it cannot do some JavaScript tasks. For example, pure PHP cannot create JavaScript alerts. It is impossible to turn all JavaScript into PHP, but you can use a very simple solution. A PHP script can include any JavaScript you like.
Instructions
-
-
1
Create a JavaScript file. To do this, open a new document in your text editor. Copy and paste this JavaScript code into it:
alert('A JavaScript file from a PHP script!');
Save this file to any folder on your PHP server. Name the file “alert.js”.
-
2
Create a PHP file. Open another new document in your text editor. Copy and paste this PHP code into it:
<?php
print '<script type="text/javascript" src="alert.js"></script>';
?>
Save this file to your server in the same folder as before. Name the file “page.php”.
-
-
3
View the result. Open your browser and load “page.php” from the server. A JavaScript alert box should appear when the page starts loading. (If it doesn't, check that your server is running and that you typed the full URL correctly). Although PHP cannot create alert boxes, you just tricked it into making one. It worked because PHP’s Print method simply writes any text-string into a web page. If that string makes sense as JavaScript, then a browser will treat it as JavaScript.
-
1
Tips & Warnings
This method works for any size of external JavaScript file. This means you don’t need to “translate” your JavaScript applications into pure PHP. Turning JavaScript into PHP just involves making it work with PHP.
You can write any JavaScript code directly inside the string variable of PHP’s Print method. If you try this, take great care with your syntax, especially your single (’) and double (”) quotes. It is much easier to keep JavaScript in an external file, as shown in the example.
To turn "page.php" into a proper web page, just add standard hypertext markup language (HTML) to it. You can have the example PHP code in either the head section or the body section.
PHP and JavaScript work in two very different ways. PHP is a “server-side” language. This means that PHP communicates with servers, not browsers. JavaScript is a “client-side” language. This means that JavaScript communicates with browsers, not servers. This is why PHP has to include some JavaScript to make a browser display an alert box. Equally, it is why JavaScript can only make content “on the fly” but PHP can genuinely write it into a page.
PHP scripts work only on a server on which PHP is already installed.
References
Resources
- Photo Credit www image by creative from Fotolia.com