Paragon
Paragon

Reputation: 2722

Unable to use returned JSON

I've got a simple bit of code in PHP that queries, grabs the resulting array, and echoes it so I can pick it up in javascript:

echo json_encode($emailQuery->result);

(the ->result part is Expression Engine; it returns an array of the result set)

My javascript to receive the code is as follows:

$.post("/dev/onboardingEmailsSubmit", loadInfo, function(data) {
    console.log(data);
});

When I output data, it outputs the entire string as I would expect, ie. {[varname:"value", etc.]}. But data['varName'], it is undefined. data.varName is also undefined. data[0] is the first character of the JSON string, leading me to believe that javascript is not at all using this as an object. data[1] is the 2nd character, etc.

Does anyone know what's going on here? I need to be working with an array of data.

Upvotes: 1

Views: 137

Answers (2)

gen_Eric
gen_Eric

Reputation: 227200

$.post("/dev/onboardingEmailsSubmit", loadInfo, function(data) {
    console.log(data);
}, 'json');

jQuery will parse the JSON, if you pass 'json' as 4th param to $.post.

Upvotes: 0

Felix Kling
Felix Kling

Reputation: 816334

Sounds like you have not parsed the JSON. How should the browser or jQuery know that the response you get is JSON? (also see @Marc's comment)

You can pass 'json' as fourth parameter to $.post [docs] to let jQuery parse the response for you.

Upvotes: 6

Related Questions