To Set PHP Variable in JavaScript, we need to define a JS variable and assign a PHP value using a PHP tag with single or double quotes.
Most of the time you have to set PHP variable value in JavaScript. If there is only a simple variable like a string or any integer then you can simply echo on the JS variable with a PHP tag.
For example, if you have a string value on the PHP variable and want to assign it and console it on JS.
1 2 3 4 5 6 7 8 |
<?php $nrmlString = 'Lorem ipsum dolor sit amet'; ?> <script type="text/javascript"> var normalText = '<?php echo $nrmlString; ?>'; console.log(normalText); </script> |
Output:
Lorem ipsum dolor sit amet
If you have any array value in PHP and you want to get that value on the same JavaScript variable then,
1 2 3 4 5 6 7 |
<?php $stArray = array('Lorem', 'ipsum', array('dolor', 'amet')); ?> <script type="text/javascript"> var phpArray = <?php echo json_encode($stArray); ?>; console.log(phpArray); </script> |
Output on Console:
(3) [“Lorem”, “ipsum”, Array(2)]
0: “Lorem”
1: “ipsum”
2: (2) [“dolor”, “amet”]
Complete Example to Set PHP Variable in JavaScript
1 2 3 4 5 6 7 8 9 10 11 |
<?php $nrmlString = 'Lorem ipsum dolor sit amet'; $stArray = array('Lorem', 'ipsum', array('dolor', 'amet')); ?> <script type="text/javascript"> var normalText = '<?php echo $nrmlString; ?>'; console.log(normalText); var phpArray = <?php echo json_encode($stArray); ?>; console.log(phpArray); </script> |
Output:
Here is a complete example, How to define PHP variables in JavaScript.
Pass PHP Variable as Parameter in JavaScript Function
1 2 3 4 5 6 7 8 9 10 11 |
<?php $nrmlString = 5; ?> <script type="text/javascript"> var normalText = '<?php echo $nrmlString; ?>'; function printaddition(userPHPNumber){ alert(parseInt(userPHPNumber)+5); } printaddition(normalText); </script> |
Output:
Alert 10
In this example Pass PHP Variable as Parameter in JavaScript Function,
- First, we define a PHP integer and then we create a JS function and
- Take the PHP variable on our JS variable.
- Then we call that function with the JS variable as a parameter, Which alerts the addition of numbers.
I think this is the complete guide about accessing PHP variables in JavaScript and also set PHP variable value to JS variable.
We also use parseInt()
to convert string to integer in JS. You also read know more from here https://www.w3schools.com/jsref/jsref_parseint.asp
Also Check and Run Live on https://codingtasks.net/php-online-editor/
Also Check:
- How Does JavaScript Filter Function work (Complete Guide With Example)
- Get Selected Date From Calendar in PHP using Ajax
- Auto Add Country Code in Input using JavaScript
- How to Validate Date String in PHP
Happy Coding..!
[…] How to Set PHP Variable in JavaScript With Example […]
[…] How to Set PHP Variable in JavaScript With Example […]