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.

share|improve this question

38% accept rate
feedback

closed as exact duplicate by Peter Mortensen, Fluffeh, DCoder, FelipeAls, Donal Fellows Aug 19 at 22:03

This question covers exactly the same content as earlier questions on this topic; its answers may be merged with another identical question. See the FAQ for guidance on how to improve it.

4 Answers

up vote 8 down vote accepted

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.

share|improve this answer
1  
rhino is correct, json_encode escapes the variable. – Jonah Nov 26 '10 at 17:51
1  
W3C states that The type attribute must be specified for each SCRIPT element instance in a document. – stillstanding 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
1  
@stillstanding: Be specific: W3C states where? It's not required in HTML5. – casablanca Nov 26 '10 at 17:54
1  
@stillstanding: I wouldn't trust W3Schools as much as the actual spec. See 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
show 3 more comments
feedback

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>
share|improve this answer
1  
+1. Tested, and json_encode does quote and escape strings properly. – Jonah Nov 26 '10 at 18:16
feedback

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

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

and then in your JS:

var size_of_widget = document.getElementById("metadata-size-of-widget").title;
share|improve this answer
feedback

Not the answer you're looking for? Browse other questions tagged or ask your own question.