Shah Rushabh
Shah Rushabh

Reputation: 13

jQuery How to retrieve and alert JSON data

JSON:

[  
   {  
      "ID":"25",
      "Serial":"1",
      "Purchase_id":"8",
      "Item":"23",
      "Unit":"1",
      "HSN":"84212120",
      "Quantity":"10",
      "Purchase_rate":"100",
      "Discount":"10",
      "Discount_2":"5",
      "Net_rate":"85.5",
      "CGST_Percentage":"9",
      "SGST_Percentage":"9",
      "IGST_Percentage":"0",
      "Rate_after_tax":"100.89",
      "CGST":"76.95",
      "SGST":"76.95",
      "IGST":"0",
      "Net_amount_without_tax":"855",
      "Net_amount":"1008.9"
   }
]

jQuery:

$.ajax({
    method: "POST",
    url: formsubmission,
    data: data,
    success: function(response) {
        var data = JSON.parse(response);
        alert(data.ID);
    }
})

Anyone can please help me why alert is coming with an undefined message. How can I resolve i8t and How can I alert 25 instead of undefined?

Upvotes: 0

Views: 1503

Answers (2)

jeevanswamy21
jeevanswamy21

Reputation: 168

var response =`[{"ID":"25","Serial":"1","Purchase_id":"8","Item":"23","Unit":"1","HSN":"84212120","Quantity":"10","Purchase_rate":"100","Discount":"10","Discount_2":"5","Net_rate":"85.5","CGST_Percentage":"9","SGST_Percentage":"9","IGST_Percentage":"0","Rate_after_tax":"100.89","CGST":"76.95","SGST":"76.95","IGST":"0","Net_amount_without_tax":"855","Net_amount":"1008.9"}]`;

    var data = JSON.parse(response);
    for (var i = 0; i < data.length; i++) {    
      alert(data[i].ID);
    } 

Upvotes: 0

guest271314
guest271314

Reputation: 1

The object is at index 0 of the resulting Array of the parsed response. You can use bracket notation to reference element at index 0 of the JavaScript object

let response =`[{"ID":"25","Serial":"1","Purchase_id":"8","Item":"23","Unit":"1","HSN":"84212120","Quantity":"10","Purchase_rate":"100","Discount":"10","Discount_2":"5","Net_rate":"85.5","CGST_Percentage":"9","SGST_Percentage":"9","IGST_Percentage":"0","Rate_after_tax":"100.89","CGST":"76.95","SGST":"76.95","IGST":"0","Net_amount_without_tax":"855","Net_amount":"1008.9"}]`;

let data = JSON.parse(response);

alert(data[0].ID);

Upvotes: 2

Related Questions