51

Possible Duplicate:
How to access PHP variables in JavaScript or jQuery rather than <?php echo $variable ?>

Is there any way to get access to a PHP variable in JavaScript?

I have a variable, $a, in PHP and want to get its value in a JavaScript variable.

Community
  • 1
  • 1
sahil
  • 1,108
  • 3
  • 15
  • 25

3 Answers3

118

You can't, you'll have to do something like

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

You can also load it with AJAX

rhino is right, the snippet lacks of a type for the sake of brevity.

Also, note that if $php_var has quotes, it will break your script. You shall use addslashes, htmlentities or a custom function.

metrobalderas
  • 5,180
  • 7
  • 40
  • 47
  • 2
    rhino is correct, json_encode escapes the variable. – Jonah Nov 26 '10 at 17:51
  • 3
    W3C states that `The type attribute must be specified for each SCRIPT element instance in a document.` – bcosca Nov 26 '10 at 17:51
  • Right, he was probably just omitting it for the sake of brevity. – Jonah Nov 26 '10 at 17:53
  • 3
    @stillstanding: Be specific: W3C states where? It's not required in HTML5. – casablanca Nov 26 '10 at 17:54
  • See for yourself: `The **required** type attribute specifies the MIME type of the script.` http://www.w3schools.com/html5/tag_script.asp – bcosca Nov 26 '10 at 17:58
  • 5
    @stillstanding: I wouldn't trust W3Schools as much as the actual spec. See http://www.w3.org/TR/html5/scripting-1.html#script -- The type attribute gives the language of the script or format of the data. ... The default, which is used if the attribute is absent, is "text/javascript". – casablanca Nov 26 '10 at 18:02
  • Interesting. Here's the tag specification. Nowhere that I can see does it mention that type is required. Time to update my brain to HTML5. http://www.w3.org/TR/html-markup/script.html – Jonah Nov 26 '10 at 18:13
  • json_encode() escapes quotes. – Jonah Nov 26 '10 at 18:32
51

metrobalderas is partially right. Partially, because the PHP variable's value may contain some special characters, which are metacharacters in JavaScript. To avoid such problem, use the code below:

<script type="text/javascript">
var something=<?php echo json_encode($a); ?>;
</script>
rhino
  • 13,543
  • 9
  • 37
  • 39
7

I'm not sure how necessary this is, and it adds a call to getElementById, but if you're really keen on getting inline JavaScript out of your code, you can pass it as an HTML attribute, namely:

<span class="metadata" id="metadata-size-of-widget" title="<?php echo json_encode($size_of_widget) ?>"></span>

And then in your JavaScript:

var size_of_widget = document.getElementById("metadata-size-of-widget").title;
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
yitznewton
  • 800
  • 8
  • 20