What's the best way to pass a PHP variable to Javascript? [duplicate]

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?



General Data Passing

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

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

then returns a JavaScript object literal like this:

    "test" : "var",
    "intvalue" : 1

You can directly echo it into a JavaScript variable on your page, e.g.:

var data = <?php echo json_encode($data)?>;

...or request it via Ajax (e.g. using jQuery's getJSON).

Outputting to attributes on tags

If you just need to output a string to an attribute on a tag, use htmlspecialchars. Assuming a variable:

$nifty = "I'm the nifty attribute value with both \"double\" and 'single' quotes in it.";

...you can output it like this:

<div data-nifty-attr="<?php echo htmlspecialchars($nifty)?>">...</div>

...or if you use short tags:

<div data-nifty-attr="<?= htmlspecialchars($nifty)?>">...</div>
  $my_php_var = array(..... big, complex structure.....);
<script type="text/javascript">
  my_js_var = <?=json_encode ($my_php_var)?>;

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


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.


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.