2

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.

1
  • @dsg Tried that and it still returns an undefined. Commented Feb 4, 2015 at 12:19

2 Answers 2

1

. 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);
Sign up to request clarification or add additional context in comments.

2 Comments

Tried that but it still returns an undefined... :<
Thanks! It works. However, do you mind checking my updated Javascript and see if it's correct?
1

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']];

5 Comments

I'm quite new doing this, do you mind elaborating or show with examples?
In your first line of php code, you are creating a string, not an object. That string is serialized as a string, and not json. You would want to work with PHP objects on the php side and not with json strings. Thats why I showed you an example of how to build the object (object)['request_id': $requestId, 'reqName': $requestName, 'reqSubject': ['English', 'A Math']]; Codeseekers Answer is correct, but basically just a workaround for your current inconsistent serialization mechanism.
Long story short: the data you are receiving in your ajax handler is an array of strings, and not an array of JSON objects. Therefore you need an additional parseJSON on each of the array items.
Alright. I understand. Thank you for the elaboration. I will try your method as well.
I did your method and I guess it feels more neater? Haha, thank you for helping!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.