Search code examples
jqueryjsonajaxgetjson

getJSON in getson


I have two JSON-Datas looking like that:

[{
  "productId": "1",
  "name": "RX7048",
  "imageUrl": "http://s7d9.scene7.com/is/image",
  "description": "Modern design.",
  "price": "229.95",
  "manufacturerId": "1"
}, {
  "productId": "2",
  "name": "RB 2132 52 New Wayfarer",
  "imageUrl": "http://s7d9.scene7.com/is/image",
  "description": "Best Seller",
  "price": "129.95",
  "manufacturerId": "1"
}, {
  ...
}]

and

{
  "1": {
    "manufacturerId": "1",
    "name": "Ray-Ban",
    "city": "",
    "state": "",
    "website": ""
  },
  "2": {
    "manufacturerId": "2",
    ...
  }
}

I am trying to display them in a HTML website like that:

function getAllProducts() {
  $.getJSON('http://meyecare.herokuapp.com/api/v1/products', function(data) {
    var len = data.length;
    for(var i = 0; i < len; i++) {
      //get the name of the Manufacturer by Manufact.-Id         
      var w = $.getJSON('http://meyecare.herokuapp.com/api/v1/manufacturers/' + data[i].manufacturerId);

      $('#products').append("<tr><td class='name'>" + data[i].name +
                            "</td><td><img class='prodImg' src='" + 
                            data[i].imageUrl +  "'/>"+
                            "<td class='manus'>" + w.name + "</td>"+
                            "<td class='descr'>" + data[i].description+
                            "</td>" +
                            "<td>$ " + data[i].price+
                            "</td><td><span class='btn' prodId='" +
                            data[i].productId + "'>Buy me</span></td></tr>");
    }        
  });
}

It is showing me the Table with the correct Products in the correct Columns and Rows, but the column that tries to join the Manufacturers-Name shows "[object Object]" instead of the Manufacturername.

I cannot find the mistake, can anyone help me please..?


Solution

  • I guess your "Manufacturers-Name" column is the td with manus class. If that's the case, then I assume the question is why w.name does not display correctly.

    $.getJSON is asynchronous. It returns a promise instead of the actual API response. So w in this case is a promise, not the manufacturer data.

    You need to use $.getJSON the way you used it for the first time (by passing in success callback).