Serve Your PHP script as JavaScript file.
Some times we need to serve user based JavaScript files, for example
- passing your php variables to JavaScript on client side of browser.
- protecting JavaScript variables.
- setting browser cache manually for JavaScript files.
- loading user based java script files.
- for easy versification of your JavaScript files.
Download Demo
Suppose your php-javascript file “my-phpjavascript.js.php” ,now you can add this file as below example.
Client HTML code
<html> <head> <script type="text/javascript" src="my-phpjavascript.js.php"></script> </head> <body> <script> alert(site_name); </script> </body> </html>
my-phpjavascript.js.php code
<?php // this is PHP variable $sitename="My PHP development blog."; ?> //this is javascript variable var site_name="<?php echo $sitename;?>";
some browsers don’t recognize this php file as javascript ,so to make all browser compatibility we have to send javascript headers to browser ,we can do that by adding a few line of code at starting of php script.
<?php header( "Content-Type: text/javascript; charset=utf-8" ); ?>
Remember to preview this code you must installed PHP
Download Demo
Popularity: 2% [?]