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

General Data Passing

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

<?php
    $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:

<?php
$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>

Leave a Comment