0

Possible Duplicate:
I have a nested data structure / JSON, how can I access a specific value?

Basically I have a returned json object like this:

"products":[
    {
        "id": "21102165",
        "name": "Eliza J (3/4 sleeve ruched waist dress)",
    }]

My method to display it:

function getCart(){
var json = $.getJSON('https://'+storedomain+'/cart?'+fcc.session_get()+'&output=json&callback=?');
alert(json['name']);
}

However the alert displays "undefined". Where I'm I doing wrong here?

Thanks

Community
  • 1
  • 1
user208709
  • 415
  • 1
  • 7
  • 12

3 Answers3

4

$.getJSON return $.Deferred object and not a result

function getCart(){
    $.getJSON('https://'+storedomain+'/cart?'+fcc.session_get()+'&output=json&callback=?', function(data) {
        console.log(data.products[0].name);
    });
}

you can do:

function getCart(){
    return $.getJSON('https://'+storedomain+'/cart?'+fcc.session_get()+'&output=json&callback=?');
}  

$.when(getCart()).then(function(data) {
    console.log(data.products[0].name);
});
salexch
  • 2,644
  • 1
  • 20
  • 17
0

Use the success callback.

var jqxhr = $.getJSON("example.json", function(data, textStatus, jqXHR) {
  alert("success");
})
.success(function(data, textStatus, jqXHR) { alert("second success"); })
.error(function() { alert("error"); })
.complete(function() { alert("complete"); });

See the API documentation for getJSON.

Stefan
  • 5,644
  • 4
  • 24
  • 31
0

Your method should be:

function getCart(callback) {
    var url = 'https://'+storedomain + '/cart?'+fcc.session_get()+'&output=json&callback=?';
    $.getJSON(url, callback);
}

// Usage
getCart(function(data) {
    console.log(data.products); // array of car objects
});

Or you can use deffered object as explained in salexch answer.

You should become familiar with asynchronous nature of AJAX requests and with callback functions.

dfsq
  • 191,768
  • 25
  • 236
  • 258