In most web applications, static JavaScript files suit the developer 100%. However, sometimes it is the best solution to connect PHP and generate the contents of the JS file on the fly (for example, get the actual prices for products from the database and pass them on to the JavaScript program to validate the order form). How to do it?
Method one: simple
Of course, the simplest solution is to include PHP code inside the section of your HTML template, because there are chances that it will have the extension .php.
<script> var jsVar = "<?php echo $phpVar ?>"; </script>
Even if the extension of the .htm or .html template, in most cases the web server is configured to understand the inclusion of PHP code (if not, then at the end of the note there is a simple example of how to solve this problem). But as for beauty, this option is not the most elegant. It would be nice to keep the flies and cutlets apart.
Method Two: beautiful
The second solution is to configure the web server so that it parses the JavaScript files to execute the PHP code. It is enough to create a .htaccess file in the desired folder or open an existing one and add the following lines to it:
')
AddType application/x-httpd-php .js AddHandler x-httpd-php5 .js <FilesMatch "\.(js|php)$"> SetHandler application/x-httpd-php </FilesMatch>
Pro et Contra: what does it give us?
Pro- You can include PHP code in files with the .js extension and it will be automatically executed when the client accesses the JavaScript file.
- You can keep such “hybrid” scripts in a separate folder - just place the .htaccess file described above in this folder.
- If you want to keep all JavaScript files in one place (static and hybrid), then you can register a file handler with an arbitrary extension, for example, .js2 - just modify the .htaccess text a little.
- You can separate static HTML pages, templates, and JavaScript files.
Contra- Theoretically, this will cause a minimal additional load on the server, but, taking into account variations with individual folders or file extensions, the benefits seem to be superior.
Addition
To parse the web server .htm and .html files and execute the PHP code included in them, you need to add the following lines to .htaccess:
AddType application/x-httpd-php .htm .html AddHandler x-httpd-php5 .htm .html <FilesMatch "\.(htm|html|php)$"> SetHandler application/x-httpd-php </FilesMatch>
Comments, additions and exchange of experience are welcome.
FINDINGS
It is rather strange that a small note, which in fact offers only a snippet for the quick realization of a concrete practical task, caused such a heated discussion, mostly similar to attempts to show off theory. The famous habr-community in this case selflessly lynched those ideas that were not mentioned in principle in the note. Although we must pay tribute - there are still some healthy thoughts. And besides - there is “no other luxury but the luxury of human communication” (according to Exupéry)))) .