-1

I have been trying to show php variables in javascript like this:

<body>
<?php
$v = "random";
echo "<script language='javascript'> 
document.write('<?php echo($v); ?>');
</script>"
?>
</body>

But this does not show any output in the browser. Why is that?

Adrian Cid Almaguer
  • 7,815
  • 13
  • 41
  • 63

7 Answers7

5

Use PHP's string concatenation to do this:

<body>
<?php
$v = "random";
echo "<script language='javascript'> 
document.write('" . $v . "');
</script>"
?>
</body>
Sumner Evans
  • 8,951
  • 5
  • 30
  • 47
0

You have some misplaced tags. Try with this code:

<body>
<?php
$v = "random";
echo "<script language='javascript'> 
document.write('$v')";
?>
</script>
</body>

HTML Output:

<body>
<script language='javascript'> 
document.write('random')</script>
</body>
Adrian Cid Almaguer
  • 7,815
  • 13
  • 41
  • 63
0

instead

document.write('<?php echo($v); ?>');

try

document.write('$v');
Ayyanar G
  • 1,545
  • 1
  • 11
  • 24
0

You've already opened php with <?php and already invoked the echo call.

It is best to concatenate the variable by closing the quotes and using a period:

echo "<script language='javascript'> 
document.write('". $v ."');
</script>";

Like Mr.Alien said in the comments, it doesn't appear you need to echo the Javascript. You can just invoke PHP where you need to echo the variable. If your install supports short tags, you can do this:

<body>
<script language='javascript'> 
document.write('<?= $v ?>');
</script>
</body>

<?= $v ?> is a short tag for <?php echo $v; ?>

Devon Bessemer
  • 34,461
  • 9
  • 69
  • 95
0

for a good practice of programming

and for easy mainting the code between javascript and php

store the php value to a variable and use it in javascript

<?php
    $v = 'random';
?>

<script>
    // store the php variable into a javascript variable
    // for this instance you can use the javascript variable v
    // in any script file if you define the variable v to be global
    var v = '<?php echo $v; ?>';
    // print it out

    // it is more readable for other user reading it
    document.write(v);
</script>

a good link also

How to embed php in javascript?

Community
  • 1
  • 1
Oli Soproni B.
  • 2,774
  • 3
  • 22
  • 47
  • An explanation of how this works or what you've fixed would boost the answer's useful tremendously. – ssube Apr 20 '15 at 04:03
0

Try this

<input type="hidden" id="msg" value="<?php echo $v;?>">

and then call it from JS

var msg = document.getElementById('msg').value;
document.write(msg);

should work

GaLaBoOnZ
  • 81
  • 4
-1

If your goal is to see the value of the PHP variable on the web page, you could use this:

<body>
<?php $v = "random"; ?>
<p>This is the PHP variable <?php echo $v ?></p>
</body>
user2182349
  • 9,569
  • 3
  • 29
  • 41