nowiko
nowiko

Reputation: 2567

get property from data variable in ajax jQuery

I try to get value of the variable what lay in response object(data variable). Here is what I get when console.log whole data:

 {"comment_id":7,"view": ......

But when I try this to get comment_id I getting undefined:

console.log(data['comment_id']); // undefined
console.log(data.comment_id); // undefined

What I am doing wrong?

Upvotes: 0

Views: 1861

Answers (2)

fredmaggiowski
fredmaggiowski

Reputation: 2248

You have to parse the JSON string you received in a JSON Object..

see $.parseJSON (if you have jQuery)

or else in pure JS

var mjsn = JSON.parse( your_json );
console.log(mjsn['key']);
// or 
console.log(mjsn.key);

Upvotes: 2

Mark Santiago
Mark Santiago

Reputation: 463

If it is from an ajax request your content type should be application/json to make that code work

if not parse it

var json = JSON.parse(data);
console.log(json.comment_id);

Upvotes: 1

Related Questions