php variable to javascript – How to pass variables and data from PHP to JavaScript?

php variable to javascript Use AJAX to Pass the PHP Variable to JavaScript as well as javascript get php variable and access php variable in javascript Example with demo.

Passing a variable from PHP to JavaScript is super easy.

php variable to javascript

In this article, i will learn how to access php variable in jquery with tiny example. i always require to get php array variable or data variable in javascript or jquery.

How to access PHP variables in JavaScript or jQuery?

Example : use php variable in javascript

<?php
    $wlecomeStr = 'Welcome To Pakainfo';
    $members = array('Welcome', 'Pakainfo', array('paka', 'info'));
?>
<script type="text/javascript">
    var wlecomeStr = '<?php echo $wlecomeStr; ?>';
    console.log(wlecomeStr);
    var members = <?php echo json_encode($members); ?>;
    console.log(members);
</script>

How to pass JavaScript variables to PHP?

Example

<script>
   var wlecomeStr = "Welcome To Pakainfo";
</script>
<?php
   echo "<script>document.writeln(wlecomeStr);</script>";
?>

how to use js variable in php?

Example – using js variable in php

<script type="text/javascript">
var wlecomeStr= 'Welcome To Pakainfo.com';
<?php $wlecomeStr = "<script>document.write(wlecomeStr)</script>"?>   
</script>
<?php echo $wlecomeStr;?>

how to get a variable from php to javascript?

Example

<script type="text/javascript">

var wlecomeStr = "<?php echo $wlecomeStr ?>"; 


var res = <?php echo $res ?>; 
var demo_ex = "<?php echo $res ?>";

var res = "<?php echo $res ?>";
</script>

Pass Variable From PHP to JavaScript

# php 7.*
<?php
?>
<script>
var req = new XMLHttpRequest(); 
    req.onload = function() {
    console.log(this.responseText); 
 };
req.open("get", "get-players.php", true); 
req.send();
</script>

# php 7.*
<?php
$javascriptvariable = "Viratkohali";
echo json_encode($javascriptvariable); 
?>

Result

"Viratkohali"

Also Read : How To Get Javascript Variable Value In Php In Same Page?

php variable to javascript
Use JavaScript to Escape the PHP Scripts to Pass the PHP Variable to JavaScript

#php 7.x
<?php
$javascriptvariable = 'Viratkohali';
?>
<script>
   <?php
       echo "var javascriptvariable ='$javascriptvariable';";
   ?>
   console.log(javascriptvariable); 
</script>

Use the Short PHP Echo Tag, Inside the JavaScript to Pass the PHP Variable to JavaScript

#php 7.x php variable to javascript	
<?php
$javascriptvariable = 'Viratkohali';
?>
<script>
    var javascriptvariable = '<?=$javascriptvariable?>';
    console.log(javascriptvariable); 
</script>
?>

Also Read This 👉   jQuery AJAX Dynamic Treeview Menu using PHP, MySQL

Result

Viratkohali

I hope you get an idea about php variable to javascript.
I would like to have feedback on my infinityknow.com.
Your valuable feedback, question, or comments about this article are always welcome.
If you enjoyed and liked this post, don’t forget to share.