Serve your PHP file as JavaScript file

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

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="" highlight="">