0

I'd like to takover the variable from PHP to javascript. What is wrong in my script? Thanks.

<!DOCTYPE html>
<HTML>
   <HEAD>
   <META charset="UTF-8">
   <TITLE>Převzetí proměnné z PHP do Javascript</TITLE>
   </HEAD>
   <BODY>
      <?php
         $variable = 'Já jsem proměnná';
         echo $variable.'<BR />';
      ?>
      <SCRIPT>
         var x = $variable;
         document.write(x);
      </SCRIPT>
   <BODY>
</HTML>
  • 1
    possible duplicate of [How to access PHP variables in JavaScript or jQuery rather than ](http://stackoverflow.com/questions/1808108/how-to-access-php-variables-in-javascript-or-jquery-rather-than-php-echo-vari) – Jonathan Lonowski Feb 15 '14 at 23:04

4 Answers4

4

$variable is a string so the JavaScript assignment must be quoted:

var x = "<?php echo addslashes($variable); ?>";document.write(x);


Updated to json_encode (thanks Marc B).

<!doctype html>
<title>Převzetí proměnné z PHP do Javascript</title>
<meta charset="utf-8"/>
<script>
    <?php $variable = 'Já jsem proměnná - testing "double quotes" and \'single quotes\''; ?>
    var x = <?php echo json_encode($variable); ?>;
    document.write(x);
</script>
Andrew Mackrodt
  • 1,806
  • 14
  • 10
  • BAD idea. addslashes is useless in this context. addslashes shouldn't even exist anymore. You want json_encode(). – Marc B Feb 15 '14 at 23:06
0

try using something like this:

<?php $myvar = 'test' ?>
<?php echo '<script type="text/javascript">var myvar = "'.$myvar.'";</script>';

or changing

var x = $variable;

to

var x = "<?php echo $variable ?>";

should work.

Dylan Lea
  • 50
  • 1
  • 12
  • no, you don't add quotes. You use json_encode(), which does all of that for you. – Marc B Feb 15 '14 at 23:06
  • @Marc B You have to add quotes. Without it it doesn't work. I have tested it. –  Feb 15 '14 at 23:09
  • no. `$foo = 'foo'; echo json_encode($foo);` will output `"foo"`, WITH the quotes. Remember that JSON is essentially the right-hand side of a variable assignemt in Javascript, so whatever json_encode() outputs has to be valid if you directly stuff that output into the R.H.S of an assignment. The only thing you have to add is the `;` at the end of the line. `var foo = ;`. – Marc B Feb 15 '14 at 23:13
0

Use this:

var x = '<?php echo $variable; ?>';
Akhilesh
  • 1,064
  • 15
  • 28
  • 1
    No. You don't do this. You use json_encode(). You've not introduced the JS equivalent of an sql injection attack... – Marc B Feb 15 '14 at 23:07
  • Please explain your answer in brief to make it more useful for OP and other readers. – Mohit Jain May 29 '14 at 03:13
-1

you have to echo PHP directly into where you want to use it.

var x = "<?php echo $variable; ?>";
thescientist
  • 2,906
  • 1
  • 20
  • 15
  • you need to json_encode() the value, since you're outputting into a javascript context... can't just dump out a raw string and expect it to work. – Marc B Feb 15 '14 at 23:05