Passing data from PHP to JavaScript

Have you ever needed to send a PHP variable, array, or object to JavaScript? It can get complicated trying to escape the output properly. Here’s a way that always works—no escaping necessary.

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

  • $name = ‘Bob Marley’;

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.