I would take a php json object and save it in a jquery variable.
<?php
$arr = array();
for ($i = 0; $i < 5; $i++) {
$arr[] = array('id'=>$i, 'text'=>$i);
}
$arr = json_encode($arr);
?>
<input id="phpObj" type="hidden" value="" data-items='<?php echo $arr; ?>'>
browser html source display
<input id="phpObj" type="hidden" data-items="[{"id":0,"text":0},{"id":1,"text":1},{"id":2,"text":2},{"id":3,"text":3},{"id":4,"text":4}]">
For get the php object I did it this way
var data = jQuery.parseJSON($('#phpObj').data('items'));
console.log(data);
but I've this error
SyntaxError: JSON.parse: unexpected character at line 1 column 2 of the JSON data
I tried to use jQuery.parseJSON(JSON.stringify($('#phpObj').data('items')));
but with no success. SyntaxError: unterminated string literal
How can I solve this? Thanks
var data = $.parseJSON('<?php echo $arr;?>');<input id="phpObj" type="hidden" value='<?php echo $arr; ?>'>andvar data = $.parseJSON($('#phpObj').val());