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 another CMS, make sure to place it in the header.php file of your active theme.
Tired of dealing with your slow WordPress website? Email me at email@example.com and mention the code #FreeHosting10 for two free months of lightning-fast WordPress hosting. We will even migrate you for free!
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>
Note that as Sherri mentioned in the comments, if you have more complicated strings or any strings with quotes (“) in them, this will break. You’ll want to look into json encoding if needed. But for simple strings and variables, this should do the trick.
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!