Unable to parse php json encoded values ​​in JSON analysis in javascript / jquery

advertisements

Hello I am trying to parse a data result from my database into my html view. I am not quite sure what is wrong with what I'm doing.

Here is my code:

function display($dbhandler){

$sql = "SELECT * FROM users";
    foreach($dbhandler->query($sql) as $row){
        $data = array('id'=>$row['id'],
                         'email'=> $row['email'],
                         'name'=> $row['name']
                         );

        echo json_encode($data);        

    }

}

This will give me an output of:

{"id":"1","email":"Email 1","name":"Name 1"}{"id":"2","email":"Email 2","name":"Name 2"}'

Now when I return and try to parse it using $.parseJSON(result) in jQuery.

function display_list(){

        action='select';

        $.ajax({
            type:"POST",
            url:"options.php",
            data:{ action : action },
            success: function(res){
                console.log(res)
                results = $.parseJSON(res);
                console.log(results);
            }
        });
    }

I get this error:

Uncaught SyntaxError: Unexpected token { in JSON at position 66 at Function.parse [as parseJSON] () at Object.success (actions.js:16) at i (jquery-3.1.1.min.js:2) at Object.fireWith [as resolveWith] (jquery-3.1.1.min.js:2) at A (jquery-3.1.1.min.js:4) at XMLHttpRequest. (jquery-3.1.1.min.js:4)

Is there anything wrong with the data I am trying to pass? Any suggestions are welcome thanks.


Change following lines:

echo json_encode()($data);

to

echo json_encode($data);

and remove this line from the loop and put just after the loop ends. And make following changes:

success: function(res){
  var data = JSON.parse(res);
  alert(data[0].name);
}