Step 1: Declare the PHP variable.
<?php $my_php_var = 'Hello World!'; ?>
In this example, we would be using a string variable named
$my_php_var containing the string Hello World!
<script> var myJsVar = ''; </script>
myJsVar will be the one to receive the data from the PHP variable that we have created in Step 1.
Step 3: Assign the PHP variable to the JS variable.
<script> var myJsVar = '<?php echo $my_php_var; ?>'; </script>
<!DOCTYPE html> <html> <?php $my_php_var = 'Hello World!'; ?> <script> var myJsVar = '<?php echo $myPHPVar; ?>'; </script> </html>
If you might want to check if the variable
console.log(). Personally, I would recommend using
console.log() and see the output in the console.
console.log(myJsVar); //Hello World!
This should print the string Hello World! in the console tab of your debugging tools.
That’s it I hope you have learned something from this tutorial.