views:

104

answers:

4

I currently echo certain variables in hidden input fields and read them out with Javascript whenever I need them.

Me and a colleague are now thinking of generating an extra Javascript file with PHP which only contains all variables for Javascript. This way the variables already exist and there is no extra code in the HTML.

What are good ways to pass variables from PHP to Javascript? And how does our solution sound?

+1  A: 

There are 3 ways you could do it:

  • Echo them directly into the javascript source: <?echo "var user = '$user';";?>. Works, but it's messy.
  • Pass them in via an ajax request. This is the closest you can come to native variable passing, but the downside is it takes an extra HTTP request.
  • What you're doing, which is passing them by generating hidden form fields and then reading them.
ryeguy
+5  A: 

A commonly used exchange format for JavaScript is JSON. A PHP file like this:

<?php
    $data = array("test" => "var", "intvalue" => 1);
    echo json_encode($data);
?>

then returns a JavaScript object like this:

{
    "test" : "var",
    "intvalue" : 1
}

You can directly echo it into a JavaScript variable on your page or request it via Ajax (e.g. using jQuerys getJSON).

Daff
+1 - this is the obvious solution if you're thinking of generating an external file for the script. Be aware that you wouldn't be able to generate JavaScript functions using JSON, however.
Andy E
Yep, JSON is definitely easiest. Also use the `JSON_HEX_TAG` option if you're writing JSON into a `<script>` block, to prevent a `</script>` sequence in a string from prematurely ending the block (and potentially causing XSS).
bobince
+2  A: 

I use to echo them all together at the head of the HTML. Seems clean enough for my needs :)

zitronic
A: 
<?php
  $my_php_var = array(..... big, complex structure.....);
?>
<script type="text/javascript">
  my_js_var = <?=json_encode ($my_php_var)?>;
</script>
Javier