Passing data from PHP to JavaScript

Let’s say we have the following variable in PHP:

$name = 'Pass me<br>to JavaScript';

And we want to pass it to a JavaScript variable called name. Here’s the trick:

echo '<script>';
echo 'var name = ' . json_encode($name) . ';';
echo '</script>';

Using json_encode(), you’ll always get a properly formatted JavaScript object.


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