Search code examples
javascriptphpjsonparsingcodeigniter-4

Javascript "JSON.parse: unexpected character at line 2 column 1 of the JSON data"


My JSON string looks like this

{"Peter":"35","Ben":"37","Joe":"43"} 

PHP code

class Products{
    public function example(){
        $results = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
        echo json_encode($results);
    }
}

Javascript code

const xhttp = new XMLHttpRequest();
xhttp.onload = function()
{
    const obj = this.responseText;
    const obj1 = JSON.parse(obj);
    alert(obj1);

}
xhttp.open("POST", "/products/example");
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send();

I get the error in the question when I parse it in javascript.


Solution

  • When sending JSON from PHP you need to set a "Content-Type" Header and you cannot use print_r.

    <?php
    $data=json_encode($result);
    header('Content-Type: application/json');
    echo $data;
    

    Try looking at the response from you PHP script in the developer tools of your browser to ensure that you get the proper HTTP Content-Type header.