0

So, I've been trying to send an array from a php file to a script through JSON, using json_encode, but whatever I do, I keep getting the same error:

SyntaxError: JSON.parse: unexpected non-whitespace character after JSON data at line 2 column 43 of the JSON data

Now, I've used jsonlint to validate the JSON received through json_encode, but it shows as not valid.

Here's my PHP code/query:


<?php

    require_once '../../DAO/model.php';

    $cd = $_POST['cd'];

    $query = "SELECT ID,name FROM user WHERE cost_center = '$cd' order by name";      
    $results = mysqli_query($conn, $query);
    while ($row = mysqli_fetch_assoc($results)){        
        echo json_encode($row); 
    }   
    ?>


   $("#centro").change(function(){
        var id = $("#centro").val();
        $.ajax({
            url: 'insertManager.php',
            method: 'POST',
            data: 
            {'cd': id}
        }).done(function(manager){

            $('#manager').empty();
            console.log(manager);
            manager = JSON.parse(manager);
            manager.forEach(function(managers){
            $('#manager').append('<option value = "' +
 managers.id + '">' + managers.name + '</option>')

            })

        })
    });

And, just to make sure, that is part of the JSON he is generating

{
        "ID": "RXA47",
        "name": "Abraao Silva Souza"
    } {
        "ID": "F7R53",
        "name": "Adao David Bueno"
    } {
        "ID": "DP800",
        "name": "Adilson Silva"
    } {
        "ID": "C355P",
        "name": "Adolfo Filho"
    }

I need to be able to iterate through this JSON so I can append the options, but it doesn't even get to that, since it gives me the JSON syntax error, what am I doing wrong?

1
  • That's invalid JSON. You can't just concatenate objects like that, { } { }it needs to be an array. [ { }, { } ] Commented Aug 8, 2019 at 18:04

1 Answer 1

0

Try this code in code object array pass in one single array and after then array pass in json encode.

 <?php 
   require_once '../../DAO/model.php';$cd = $_POST['cd']; 
   $array[]=" ";
  $query = "SELECT ID,name FROM user WHERE cost_center = '$cd' order by name";
   $results = mysqli_query($conn, $query); 
    while ($row = mysqli_fetch_object($results))
    { 
        $array[]=$row;
      } 
    echo json_encode($array);
    ?>
Sign up to request clarification or add additional context in comments.

1 Comment

If I do that, the console gives me this error: script.js:151:13 SyntaxError: JSON.parse: unexpected end of data at line 1 column 2 of the JSON data and I can't even print out the log anymore

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.