My JavaScript code is not able to read the JSON generated by my PHP code. What's wrong?

advertisements

I'm using AJAX call and I'm generating this JSON object which is sent back to JavaScript. When I receive it in the JavaScript I'm not able to get values from it.

PHP:

echo json_encode(array("results" => array(array("user" => $member['user']),array("company" => $member['company']))));

JS:

success: function(response)
    {
        for(var i = 0;i < response.results.length; i++)
        {
          sessionStorage.setItem('user',response.results[i].user);
          sessionStorage.setItem('company',response.results[i].company);
        }
    }

I'm not able to read any values from the response that I receive.

Response that I get is in this format:

{"results":[{"user":"David"},{"company":"something"}]}

What would be the proper way of reading this JSON object?


Since you are trying to access results[0].company and results[1].user which are undefined, and since only results[1].company and results[0].user are defined in your object, if you change your PHP as follows your JavaScript should work unless response is just a string:

echo json_encode( array(
    "results" => array(
        array(
            "user" => $member['user'],
            "company" => $member['company']
        )
     )
));

If response is just a string change your JavaScript code as follows:

success: function(response)
{
    response = JSON.parse(response);

Or

dataType: "json",
success: function(response)
{