Static files of JavaScript would survive most applications but sometimes the ability to include PHP code inside JavaScript scripts and generate the content of the script files on the fly by PHP is a better option. How does one do that?
The simplest solution is to just include PHP code inside the <script></script> section of your HTML templates / web pages because chances are, the file extension is .php:
<script>
var jsVar = "<?php echo $phpVar ?>";
</script>
Even if it’s not ending in .php, such as in .html or .htm, you can configure your server to parse all .html or .htm files for any PHP code, though with a little extra server burden.
Another solution for this is to make your server parse all files ending in .js. Just create a .htaccess if it doesn’t exist in the directory in which you wish to include and run PHP code inside all .js files. Add these lines at the end of .htaccess:
AddType application/x-httpd-php .js
AddHandler x-httpd-php5 .js
<FilesMatch "\.(js|php)$">
SetHandler application/x-httpd-php
</FilesMatch>
Now you can add all the PHP code you can inside any JavaScript files with a .js extension, the server will automatically parse and run them when the client side requests the file.
You should also read:
- PHP: Run HTML as PHP
- How to include a JavaScript file inside a JavaScript file?
- PHP: Run .CSS files as PHP
- PHP and JavaScript Variable / Value Transfer / Exchange: How to pass variable values from PHP to JavaScript or JavaScript to PHP?
- Use PHP to handle all incoming URL requests in a SEO friendly manner


Facebook
Twitter
Google Plus
{ 2 comments… read them below or add one }
You could also create a file with a .php extension that returns all the proper headers, and then alias it with mod_rewrite.
This is an alternative to configuring your server to parse .js files if you don’t have the ability to do this.
the best method good bro
{ 6 trackbacks }