Executing PHP code inside a .js file

EDIT: The script type should always be text/javascript as application/javascript may break compatibility with older browsers (I think IE8 and earlier will ignore the script tag with that type). The Content-type, however, should still be application/javascript.


You can’t mix in php into a .js file, the way you would with a normal .php file, since the .js file is not preprocessed by the .php engine the way your .php files are.

The most typical way to do this–including php in a js file–is to just have inline JS (stuff between <script> tags) in your .php file. Then it will work as expected.

Another way to go is to make a js file within php, so start your .php file with

<?php
header("Content-type: application/javascript");
?>
var jsvar="something";
var othervar="<?php echo $phpVar; ?>";
//<?php //some php ;?>

and then include it on your page like this

<script src="https://stackoverflow.com/questions/23574306/myjs.php" type="text/javascript"></script>

Leave a Comment