Taking a variable from PHP and sending it to javascript seems like a really simple thing to do. But it’s not. I’m sure if you ended up here, you’ve tried and tried to get it to work with little success. I’m not sure what the people online are talking about, none of those solutions seem to be functional in most situations.
But there IS an easy way. It’s just as simple as I’m sure you’ve imagined it would be. Essentially, all you are going to be doing is defining your PHP variable and then defining your javascript variable with a PHP echo. The trick? Do it in your site’s
section. Let’s take a look at an example.
1 2 3 4 5 |
<head> <title>Test Page from https://pagecrafter.com</title> <?php $our_php_variable = 'mittens'; ?> <script> our_js_variable = "<?php echo $our_php_variable; ?>"</script> </head> |
That’s all it takes! Remember, it’s key to include this in the HEAD section of our site, otherwise it won’t work. But the beauty here is that you can now use our_js_variable in javascript anywhere we want, and it will have the value “mittens”. Nothing more to it!