FFish FFish - 9 months ago 79
PHP Question

Access PHP var from external javascript file

I can access a PHP var with Javascript like this:

$fruit = "apple";
$color = "red";

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

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

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


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

Don Don

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:

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