I find that putting the following code into the
<head> section of my website is the most foolproof method:
$php_variable = 'string'; //Define our PHP variable. You can of course get the value of this variable however you need.
<script> js_variable_name = "<?php echo $php_variable; ?>";</script>
A few things to keep in mind for this:
1. The PHP variable needs to be defined before the JS one.
2. The JS variable needs to be defined before you actually use it anywhere. This seems obvious, but if you forget this fact and try to put this declaration into the footer of your site and then use it in the content, you’ll find it doesn’t work! That’s why I like to put this in the head section of my website. Or, if you were in WordPress or other CMS, make sure to place it in the header.php file of your active theme.
Additionally, you should be aware that if your variable is not a string and is instead a number, you would want to define it without the quotes around it, i.e.:
<script> js_variable_name = <?php echo $php_variable; ?>;</script>
Hard to go wrong with any of this. There are of course more complicated ways to use this, but I’m not going to go into any of those here. Let me know if you have any problems!