2

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

2
  • directly do this :- var data = $.parseJSON('<?php echo $arr;?>'); Commented Mar 27, 2016 at 18:59
  • Or <input id="phpObj" type="hidden" value='<?php echo $arr; ?>'> and var data = $.parseJSON($('#phpObj').val()); Commented Mar 27, 2016 at 19:01

2 Answers 2

2

The JSON string contains the same type of quotes that you use to wrap the data value. Try to use single quotes instead.

Sign up to request clarification or add additional context in comments.

Comments

1

A working example for you:-

<?php
$arr = array();
for ($i = 0; $i < 5; $i++) {
    $arr[] = array('id'=>$i, 'text'=>$i);
}
$arr = json_encode($arr);
?>
<input id="phpObj" type="hidden" data-items='<?php echo $arr; ?>'>
<script src="//code.jquery.com/jquery-1.12.0.min.js"></script>
<script type = "text/javascript">
$(document).ready(function(){
var data = $.parseJSON($('#phpObj').attr("data-items"));
console.log(data);
});
</script>

Output:- On my local screen:- http://prntscr.com/akrz2w

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.