53

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.

0

3 Answers 3

119

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.

Sign up to request clarification or add additional context in comments.

9 Comments

rhino is correct, json_encode escapes the variable.
W3C states that The type attribute must be specified for each SCRIPT element instance in a document.
Right, he was probably just omitting it for the sake of brevity.
@stillstanding: Be specific: W3C states where? It's not required in HTML5.
@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".
|
53

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>

1 Comment

+1. Tested, and json_encode does quote and escape strings properly.
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;

1 Comment

Though I'm 12 years late, though, people if you should not use this as the user can simply edit the value passed by php to js

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.