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 and then parse it into but 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?

+3


source to share


3 answers


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.

+1


source


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>

      

+1


source


Try putting json_encode in quotes.

populatePersons(JSON.parse('<?php echo json_encode($myArray);?>'));

      

Since the expected parameter is a string.

0


source







All Articles