FFish FFish - 4 months ago 30
PHP Question

Access PHP var from external javascript file

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

Don Don
Answer

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