-1

How would I access a value from PHP, retrieve it, and store it in my JavaScript variable?

Example:

<?php
   $name = "john"
?>

JavaScript:

var name = john
fragilewindows
  • 1,394
  • 1
  • 15
  • 26
Ajay Dude
  • 29
  • 5
  • 3
    Possible duplicate of [How to pass variables and data from PHP to JavaScript?](http://stackoverflow.com/questions/23740548/how-to-pass-variables-and-data-from-php-to-javascript) – jcubic May 12 '16 at 07:54
  • Can all of you guys stop giving the same answer to this question ? – Tilak Madichetti May 12 '16 at 08:03

7 Answers7

2
<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
    <?php $name = 'john';?>
    <script type="text/javascript">
        var name = '<?php echo $name; ?>';
        alert(name);
    </script>
</body>
</html>
P. Kumar
  • 207
  • 1
  • 7
0
<?php
   $name = "john";
?>

var name = '<?php echo $name; ?>'
Ralph Melhem
  • 767
  • 5
  • 12
  • If you want to pass string you need to add quotes. – jcubic May 12 '16 at 07:55
  • can we perform it without echo? – Ajay Dude May 12 '16 at 07:56
  • @AjayDude You can't, unless it's with an ajax call and an appropriate php function to return it which is an overkill to display a variable – Ralph Melhem May 12 '16 at 08:00
  • @AjayDude as mentioned above, check this answer: http://stackoverflow.com/questions/23740548/how-to-pass-variables-and-data-from-php-to-javascript If you have any trouble after trying to work on it alone, post another question and i'm sure we'll all help you – Ralph Melhem May 13 '16 at 05:52
0

try:

var name = '<?php echo $name; ?>';
Jayesh Chitroda
  • 4,987
  • 13
  • 18
0

You can echo the PHP variable into your javascript while your page is created.

<script type="text/javascript">
    var name = "<?php echo $name; ?>";
</script>

OR

<script type="text/javascript">
    var name = "<?=$name;?>";
</script>

Of course this is for simple variables and not objects.

Brijal Savaliya
  • 1,101
  • 9
  • 19
0

Generate part of your JavaScript by PHP:

<?php
   $name = "john";

   echo "<javascript>var name = \"" . $name . "\";</javascript>";
?>
fragilewindows
  • 1,394
  • 1
  • 15
  • 26
ssnake
  • 365
  • 2
  • 14
0

Eg.

<?php
   $name = "john"
?>

 <script>

 var myJSVar = <?php echo $name; ?>

 alert(myJSVar);

 </script>

In the above case, Your PHP variable must have defined before being accessed by JavaScript.

Jenson M John
  • 5,499
  • 5
  • 30
  • 46
0

Why don't you set the PHP variable inside a hidden <div> like this:

<div id="myvar" class="hidden"><?php echo $myphpvar; ?></div>

CSS:

.hidden {display: none; visibility: hidden;}

JavaScript:

var phpvar = document.getElementById('myvar').innerHTML;
fragilewindows
  • 1,394
  • 1
  • 15
  • 26
wgdev
  • 1
  • 2