ahfreak
ahfreak

Reputation: 119

Unable to get values from JSON Array and Object

In my Javascript and PHP, I've manage to do an .ajax call to get an array. However when I want to display the display the values of each object I'm unable to do so.

PHP:

$request =  '{"request_id":' .$requestId. ', "reqName":"' .$requestName. '", "reqSubject":' .json_encode($requestSubjects). '}';

array_push($requestArray, $request);

echo json_encode($requestArray);

Javascript:

$.ajax({
    type: "POST",
    url: serverURL + "getTutorRequestsProcess.php",
    data: sendTutId,
    dataType: "json",
    success: function(data){
        localStorage.setItem('pending', JSON.stringify(data));

        pending = JSON.parse(localStorage.getItem('pending'));
        console.log(pending);
    },
    error: function(jqXHR, textStatus, errorThrown){
        alert('Unable to retrieve requests.', null, 'Error','Done');
    }
});

So when I console.log(pending) it looks like this:

["{"request_id":13, "reqName":"Rin", "reqSubject":["English","A Math"]}", "{"request_id":14, "reqName":"Rin", "reqSubject":["English","E Math"]}"]

When I console.log(pending[0]), I'm able to get the first object:

{"request_id":13, "reqName":"Rin", "reqSubject":["English","A Math"]}

However when I want to get the values of the object like so, console.log(pending[0].request_id), it returns an undefined.

Would highly appreciate if someone could tell me what's wrong with my codes. Thank you.

EDIT: I'm trying to add the data into my localStorage. Updated codes to reflect what I'm doing.

Updated Javascript:

$.ajax({
    type: "POST",
    url: serverURL + "getTutorRequestsProcess.php",
    data: sendTutId,
    dataType: "json",
    success: function(data){
        localStorage.setItem('pending', JSON.stringify(data));

        pending = JSON.parse(localStorage.getItem('pending'));
        console.log(pending[0]);

        var response = jQuery.parseJSON(pending[i]);
        console.log(response.request_id);
    },
    error: function(jqXHR, textStatus, errorThrown){
        alert('Unable to retrieve requests.', null, 'Error','Done');
    }
})

Both answers by OVM and Codeseeker works and solved my question. It's sad that I can't mark both as correct since both of them have provided two different but valid solutions.

Upvotes: 2

Views: 1358

Answers (2)

ovm
ovm

Reputation: 2532

The problem is, that you are serializing strings with json_encode, not real PHP classes and properties.

This resulting json is an array of strings and not an array of objects:

["{"request_id":13, "reqName":"Rin", "reqSubject":["English","A Math"]}", "{"request_id":14, "reqName":"Rin", "reqSubject":["English","E Math"]}"]

You want a result like this

[{"request_id":13, "reqName":"Rin", "reqSubject":["English","A Math"]}, {"request_id":14, "reqName":"Rin", "reqSubject":["English","E Math"]}]

To achieve that, try to build up a standard PHP object with those properties and serialize it. Don't serialize a string that contains json.

So on the server side, replace your first line of code with this and you'd be good to go:

$request = (object)['request_id': $requestId, 'reqName': $requestName, 'reqSubject': ['English', 'A Math']];

Upvotes: 1

codeseeker
codeseeker

Reputation: 149

. is used for to access object property while [] notation is used for to access array value.

console.log(data[0]['request_id']);

Demo

Update:

Try with -

var response = jQuery.parseJSON(data0)
console.log(response.request_id);

Upvotes: 1

Related Questions