Access PHP var from external javascript file

You don’t really access it, you insert it into the javascript code when you serve the page.

However if your other javascript isn’t from an external source you can do something like:

<?php
    $color = "Red";
?>
<script type="text/javascript">var color = "<?= $color ?>";</script>
<script type="text/javascript" src="https://stackoverflow.com/questions/2928827/file.js"></script>

and then in the file.js use color like so:

alert("color: " + color);

Leave a Comment