Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't access object properties in jQuery AJAX call

When I call this code:

console.log(data);
console.log(data.email);

I get this result:

{"userName":"2","email":"2","firstName":"2","lastName":"2","isAdmin":"0","isEnabled":"1"} index.php:162
undefined 

The first console.log(data); outputs correctly. Then, I want to access the email property of the data object, and to do so I use console.log(data.email);. However, as you can see above, it says that it's, "undefined."

Why can't I access this property (or any properties)? Note: I have also tried data['email'] which didn't work, either.

like image 749
user1477388 Avatar asked Oct 19 '13 13:10

user1477388


2 Answers

I didn't realize that jQuery doesn't auto-parse the returned JSON to an object. It was just a JSON string. To fix, I just had to do this:

data = JSON.parse(data);

Cross-browser:

data = $.parseJSON(data);
like image 109
user1477388 Avatar answered Sep 24 '22 00:09

user1477388


In my case, I could show the object by console.log, but I couldn't access any attribute for a simple thing: I wasn't realizing that my JSON was wrongly structured, as an array with one single object. Then I could access its attribute using a index.

console.log(data.email);

undefined

but then I tried...

console.log(data[0].email);

[email protected]

I just fixed my model and it works perfectly. Thanks to my coleague Aaron Lil!

like image 35
victorf Avatar answered Sep 22 '22 00:09

victorf