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.