Step 1: Declare the PHP variable.
1 2 3 <?php $my_php_var = 'Hello World!'; ?>
In this example, we would be using a string variable named
$my_php_var containing the string
1 2 3 <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.
1 2 3 <script> var myJsVar = '<?php echo $my_php_var; ?>'; </script>
The PHP variable containing
1 2 3 4 5 6 7 8 9 <!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
myJsVar really contains the string
console.log(). Personally, I would recommend using
console.log() and see the output in the console.
1 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.