Skip to content
Rene Korss

Passing JSON data from PHP to HTML to Javascript

You need to escape data and handle special characters.

Passing JSON data and really any data from PHP to HTML is good to be done using data-* attributes. Passing as JSON is not as easy as string or integer because it will have quotes in it's output. It needs to be escaped so that output HTML will be valid.

PHP to HTML permalink

// Example data
$exampleData = [
'key' => 'value',
'items' => [
'multi' => 'dimensional'
]
];

echo '<div id="target-id" data-example="'.htmlspecialchars(json_encode($exampleData), ENT_QUOTES, 'UTF-8').'">';

data-example is just made up attribute. You can replace example with whatever you like and add multiple data-* attributes if needed.

ID of target-id is added to element so we can easily target it in javascript.

HTML to Javascript permalink

Plain Javascript

JSON.parse(document.querySelector('#target-id').dataset.example) // object

jQuery

$('#target-id').data('example'); // object

Now we have our custom data in Javascript and can easily use it as it is object.