Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using PHP in .JS file?

So I'm trying to use PHP in a .js file, here's what I have so far.

.htaccess (any *.api.js will be processed as PHP)

<FilesMatch "^.*?api.*?$">
SetHandler php54-script
</FilesMatch>

map.api.js

<?php
header("Content-type: application/javascript");
//my php here
?>

//my javascript here

.php files all include

<script type="text/javascript" src="map.api.js"></script>

For some reason this isn't working, and after much research I can't find a solution.

In the chrome developer tools I get an error, Uncaught SyntaxError: Unexpected token < - pretty self explanatory, it isn't expecting <?php at the top of the map.api.js file.

Anyone else here tried using PHP in a .js file before? If there is a better solution I'd like to know as I can't find much on Google.

like image 644
Ryan Butterworth Avatar asked Dec 19 '22 20:12

Ryan Butterworth


1 Answers

Create an file with php extension and include it in your website as javascript.

map.api.js

<?php
header("Content-type: application/javascript");
//my php here
?>
//my javascript here

In your HTML File:

<script type="text/javascript" src="map.api.php"></script>

If you wan't to hide the php extension, you can work with mod_rewrite (Apache):

RewriteEngine on
RewriteRule ^map.api.js$ map.api.php
like image 139
take Avatar answered Dec 21 '22 11:12

take