Access PHP var from external javascript file

FFish picture FFish · May 28, 2010 · Viewed 84.2k times · Source

I can access a PHP var with Javascript like this:

<?php
    $fruit = "apple";
    $color = "red";
?>

<script type="text/javascript">
    alert("fruit: " + "<?php echo $fruit; ?>"); // or shortcut "<?= $fruit ?>"
</script>

But what if I want to use an external JS file:

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

externaljs.js:

alert("color: " + "<?php echo $color; ?>");

Answer

Don picture Don · May 28, 2010

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);