I'm looking to pass an arbitrary array from PHP to JavaScript while properly escaping. I'm leaning on using base64 and I imagine that base64 isn't data attribute safe, so as a good developer I am esc_attr the data. Is there a right
way to make sure that the base64 data maintains its integrity in JavaScript?
Here's a contrived example -- that works fine -- because the esc_attr does not modify the integrity of the base64 encoding.
<?php
$array = [
[
'the' => 'quick',
'brown' => 'fox'
],
[
'test' => 'test',
'foo' => 'bar'
]
];
$values_json = base64_encode( json_encode( $array ) );
?>
<input id="check" type="checkbox" data-value="<?php esc_attr_e( $values_json ); ?>"> Foobar
<script>
var checkbox = document.getElementById(id);
checkbox.addEventListener('click',
function () {
console.log(JSON.parse(atob(this.dataset.value)));
}
);
</script>
In my research I came across this solution for handling this using JSON - however the way I am getting the data I don't have an easy way to key the data to retrieve it by using the key as a data attribute.