0

I have trouble on how to display the output of my json into success, by writing +response+ it will display [object Object]. The output will change based on id, so i think i dont need to use foreach? :/

View:-

function getItemDetails(item_id){

$.ajax({
    type:'GET',
    url: './itemDetails/'+item_id,
    datatype: 'json',

    success: function(response){
      console.log(response);
      $('#modalTitle').text("TITLE");
      $('#variants-area-inside').append('<label class="form-control-label">'+response+'</label>');
    }
 });
}

Console output:-

{
  "data": {
    "name": "Fried Chicken Wings",
    "id": 99,
    "extras": [],
    "options": [
      {
        "id": 1,
        "item_id": 99,
        "name": "Size",
        "options": "small,medium"
      }
    ],
    "variants": [
      {
        "id": 1,
        "price": 13,
        "options": "{\"1\":\"small\"}",
        "item_id": 99,
       }
    ],
    "has_variants": true,
    "description": "Fried Chicken Wings"
  }
}
cdogol
  • 155
  • 11
  • Whether you need `forEach()` or not depends on what output you're trying to create - can you edit the question to include an example of this. You will at least need to output the properties values of the object, or their child arrays, not the object as a whole (which is why you see the current output). – Rory McCrossan Jun 18 '21 at 08:41
  • Sorry, this is my first time using ajax and i don't really get what you mean :/ – cdogol Jun 18 '21 at 08:50
  • I mean, can you edit the question to show the HTML output you're expecting to see instead of the `[Object object]` string – Rory McCrossan Jun 18 '21 at 08:50
  • Okay, updated! I want to output the options.. – cdogol Jun 18 '21 at 08:55
  • No, that's an image of the HTML. Please add the *acutal HTML by copying and pasting it* – Rory McCrossan Jun 18 '21 at 09:01

1 Answers1

2

You could do it like this:

function getItemDetails(item_id){

$.ajax({
    type:'GET',
    url: './itemDetails/'+item_id,
    datatype: 'json',

    success: function(response){
      console.log(response);
      $('#modalTitle').text("TITLE");
      response.data.options.forEach(option => {
          $('#variants-area-inside').append('<label class="form-control-label">' + option.options+'</label>');
      });
    }
 });
}
Mario Varchmin
  • 3,704
  • 4
  • 18
  • 33
  • Does this mean i need to use foreach? Let say i want to get the output of Fried Chicken Wings name, how do I do that? – cdogol Jun 18 '21 at 09:28
  • 1
    @cdogol That would be `response.data.name`. You need `forEach` only, if you want to access properties in the `options` array. – Mario Varchmin Jun 18 '21 at 09:31
  • But why everytime i click on it, the output will keep adding. I've attached the image on the question :/ – cdogol Jun 18 '21 at 09:34
  • I don't know, where you are clicking. If every click executes your getItemDetails() function, then it will keep adding. – Mario Varchmin Jun 18 '21 at 09:39