The best approach is to think Javascript as PHP code.
The basic steps are:
- Create a .htaccess file that redirects all JS files (.js) to a index file.
- In this index file load JS file as a PHP module (
require "script/$file"
)
- Modify all JS files as you need. Now you can embed PHP code.
For instance, add to your .htaccess this line:
RewriteRule \.js$ index.php
In your index.php file put something like this:
// Process special JS files
$requested = empty($_SERVER['REQUEST_URI']) ? "" : $_SERVER['REQUEST_URI'];
$filename = get_filename($requested);
if (file_ends_with($requested, '.js')) {
require("www/script/$filename.php");
exit;
}
And finally in your file.js.php you can embed PHP, use GET and POST params, etc:
<?php header("Content-type: application/x-javascript"); ?>
var url = "<?php echo $url ?>";
var params = "<?php echo $params ?>";
function xxxx()....
....
In addition, a trick to skip file cache is to add a random number as javascript parameter:
<script type="text/javascript" src="scripts/file.js?a=<?php echo rand() ?>"></script>
Also, as said in a comment, if your webserver don't allow to modify the .htaccess
, you can just ask for the PHP file directly:
<script type="text/javascript" src="file.php"></script>