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="file.js"></script>

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

alert("color: " + color);

You can also access data from php script in Javascript (I'll use jQuery here) like this

Create input hidden field within you php file like this

<input type="hidden" id="myPhpValue" value="<?php echo $myPhpValue ?>" />

in your javascript file:

var myPhpValue = $("#myPhpValue").val();
//From here you can the whaterver you like with you js Value
if(myPhpValue != ''){
//Do something here
}

This will do the job as well :)


What I've seen done is let .js files run through the php interpreter. Which I can not recommend.

What I do recommend is fetching the values through AJAX and have the PHP file return the value to the JS file. Which is a much cleaner method.


First of all you have to understand that no program can actually have access to the other program's variable.

When you realize that, the rest is simple.
You can either set up a js variable in the main file and then include your external js, or make this external js dynamic, generated by PHP as well