Passing JSON data from php to html-data attribute and then to Javascript

You need to escape data and handle special characters.

<div data-side="front" data-params="<?php echo htmlspecialchars(json_encode($dataParams), ENT_QUOTES, 'UTF-8'); ?>">

And get it with jQuery:

$('[data-side="front"]').data('params'); // object

or javascript

JSON.parse(document.querySelector('[data-side="front"]').dataset.params); // object

Leave a Comment