Why am I getting the error "unexpected non-spaces after JSON data"
Can anyone tell me what the problem is:
I am iterating over a PHP array in javascript like this:
<?php
$myArray=array();
foreach ($persons as $person) {
array_push($myArray,$person['id']);
}
?>
$(document).ready(function() {
populatePersons(JSON.parse(<?php echo json_encode($myArray);?>));
});
So basically I echo from the PHP array to jsonand then parse it into javascriptbut I am getting this error in my console log:
SyntaxError: JSON.parse: unexpected non-whitespace character after JSON data
Can anyone tell me what I am doing wrong?
source to share
Can anyone tell me what I am doing wrong?
While json_encode
generating JSON, you echo
inject it into JavaScript. Essentially, this will be interpreted as a JavaScript array literal, not a string containing JSON. Hence, you cannot use JSON.parse
.
Just get rid of it:
populatePersons(<?php echo json_encode($myArray);?>);
If you've looked at the generated code, you would like:
populatePersons(JSON.parse([1,2,3]));
But JSON.parse
expects the line(containing JSON). Since JavaScript does the type conversion, it converts the array to a string first, which probably won't result in valid JSON.
Again: you already have an array, no need to parse anything.
source to share
This is because you were feeding the JSON.parse array. Just get rid of JSON.prase in your javascript and replace it with JSON.stringify if you are trying to render json. If not, then json_encode ($ myArray) should be sufficient for operations.
<div id = 'test'></div>
<script>
var test = document.getElementById('test');
test.innerHTML = JSON.stringify(<?php echo json_encode($myArray)?>);
</script>
source to share