user123_456
user123_456

Reputation: 5805

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

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?

Upvotes: 1

Views: 134

Answers (2)

aperl
aperl

Reputation: 144

In your JSON response your result contains an array with 2 objects. The first containing the user and the second containing the company. However, the your for loop you expect both elements in the array to have both user and company. It looks like you are trying to just send one user and their company. If that is the case then your code should be as follows:

PHP:

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

JS:

success: function(response) 
    {
        sessionStorage.setItem('user',response.results.user);
        sessionStorage.setItem('company',response.results.company);
    }

Your response will look like this.

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

Upvotes: 0

kaan_atakan
kaan_atakan

Reputation: 4047

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) 
{

Upvotes: 2

Related Questions