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>