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; ?>");
externaljs.js is a static file. Of course it can't access PHP data. The only way to pass PHP data to a js file would be to physically alter the file by writing to it in your PHP script, although this is a messy solution at best.
Edit in response to Ólafur Waage's answer: I guess writing to the js file isn't the only way. Passing the js through the PHP interpreter never crossed my mind (for good reason).
2017-2018 and above solution:
Since nobody bringed it up yet and I guess no one thought of combining the functions
base64_encode
andjson_encode
yet, you could even send PHP Array variables like that:Then you could just load your desired js file with the parameter for a query string like this:
echo '<script type="text/javascript" src="js/main.php?string='.$string.'&array='.$array.'">';
Then
js/main.php
will look like this for example. You can test your variables this way:The following will then output when you open your
index.php
. So you see, you don't openjs/main.php
and you still got the javascript functionality from it.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:
and then in the file.js use color like so:
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
Don solution is good, furthermore if you want to use a php array in an external javascipt this can help you:
PHP:
HTML:
Javasript: (You can now use the array like a normal Javascript array)
You can
include()
them just as you would anything else:This will basically render the external file as inline js. The main disadvantage here is that you lose the potential performance benefit of browser caching. On the other hand, it's much easier than re-declaring your php variables in javascript.