mike mike - 10 months ago 74
Javascript Question

JSON.parse object returning undefined values

I have an ajax request that returns some pretty basic data from a form submit, as shown.


if ( ! empty($errors)) {

// if there are items in our errors array, return those errors
$data['success'] = false;
$data['errors'] = $errors;
} else {

$outputArray = array();

$outputArray[] = array(
'students' => base64_encode($_POST['students']),
'sub' => $_POST['subject'],
'topic' => $_POST['topic'],
'class' => $_POST['class'],
'checked' => $_POST['checked'],
'pronoun' => $_POST['slider']

// if there are no errors process our form, then show a message of success and provide a true success variable
$data['success'] = true;
$data['message'] = json_encode($outputArray);

// return all our data to an AJAX call
echo json_encode($data);


type: 'POST',
url: 'processBatch.php',
data: formData,
dataType: 'json',
encode: true

.done(function(data) {
if (!data.success) {
// error handling goes here. Removed for clarity.
} else {

var obj1 = $.parseJSON(data.message);
var obj2 = JSON.parse(data.message);

console.log("Subject is: " + obj1.sub);
console.log("Subject is: " + obj2.sub);

On the face of it, all seems good - the returned data seems to be valid JSON (JSONlint clears it as being valid), but when I use
to convert it to an object, and try to reference the values in that object, the returned value is always undefined. I've also tried
and the result is the same.

Everything looks okay to me, so any advice would be appreciated.


"students": "TWlrZQpCb2IK",
"sub": "English",
"topic": "Test topic",
"class": "Test classname",
"checked": "WzEsNSw5XQ==",
"pronoun": "2"

Answer Source

Your JSON is an array. Use array index while accessing the element.

console.log("Subject is: " + data.message[0].sub);

Another approach is to restructure the array returned from AJAX file i.e. change $outputArray[] to $outputArray. Below is the example

$outputArray = array();

$outputArray = array(
    'students' => base64_encode($_POST['students']),
    'sub' => $_POST['subject'],
    'topic' => $_POST['topic'],
    'class' => $_POST['class'],
    'checked' =>  $_POST['checked'],
    'pronoun' => $_POST['slider']

Now, in JS file you can access element directly without array index.

 console.log("Subject is: " + data.message.sub);