SuperNinja
SuperNinja

Reputation: 1596

Ajax return, json data

I am using a ajax request with the following call to function.

var test = initBuild(id);
    test.success(function (data){
    console.log(data);
});

The data being returned looks like

{"built_when":{"id":"43701","clientId":"245","name":"Big Ass Gallery","productId":"0","desc":null,"bgColor":"#000000","fontColor":"ffffff","sort":"43701","clientRef":"205","isFeatured":"0","created":"1367356190","views":"0","finish":"0","isArchive":"0","showMailShare":"0","hardPageFlip":"0","hardCoverFlip":"0","isTemp":"0","agreement":"0","maxChange":"0","countChange":"0","verticalFlip":"0","musicSwitch":"0","showFbShare":"0","twitter":null,"email":"0","pageHeight":"1000","pageWidth":"1391"}} 

I am trying to access by data.built_when.id, but it's returning null. What am I missing on this one.

Thanks

Upvotes: 1

Views: 71

Answers (2)

Arun P Johny
Arun P Johny

Reputation: 388316

If you are sure about the return type of the ajax request to be always json then you can set dataType: 'json' to the ajax option.

Ex:

$.ajax({
    url: '',
    dataType: 'json',
    ....
})

Upvotes: 1

Explosion Pills
Explosion Pills

Reputation: 191749

It's being returned as a string. Use data = $.parseJSON(data); to convert it to JS constructs. Alternatively, you could set the Content-type: application/json header on the server side when you emit the JSON

Upvotes: 2

Related Questions