Behseini Behseini - 7 months ago 19
Javascript Question

How To Append Ajax Response (Array Of Objects) To Tbody of A Table

Can you please help me to figure it out how to append reciving data from Ajax into a tbody of an existing table?

In my HTML I have a Table Like:

<table id="example" class="table table-striped table-bordered dt-responsive nowrap" cellspacing="0" width="100%">
<thead>
<tr>
<th valign="middle" class="c-font">Projects </th>
<th valign="middle" class="c-font">Road Length (Km)</th>
<th valign="middle" class="c-font">Powerline Length (Km)</th>
<th valign="middle" class="c-font">Penstock (Km)</th>
<th valign="middle" class="c-font">Installed Capacity (MW)</th>
<th valign="middle" class="c-font">Annual Firm Energy (GW/h)</th>
<th valign="middle" class="c-font">Cost of Energy ($/MWh)</th>
<th valign="middle" class="c-font">Footprint (Km)</th>
<th valign="middle" class="c-font">Cost Per Year ($)</th>
</tr>
</thead>
<tbody> </tbody>
</table>


and js file is like

request.done(function(data) {
console.log(data);
});


which the output in console looks like

enter image description here

these are the values to be place in the
>tr><td></td></tr>


AnnualFirmEnergy: "91.2335550"
CostOfEnergy: "183.835765"
CostPerYear: "16771990.38"
Footprint: "182.3077770"
InstalledCapacity: "31.320802"
Penstock: "5000.000000"
PowerLineLength: "37.384781"
ProjectID: "12910"
RoadLength: "29.350976"

Answer

Try using $.each()

request.done(function(data) {
  $.each(data, function(key, value) {
      var tr = $("<tr />")
     $.each(value, function(k, v) {
       tr.append(
         $("<td />", {
           html: v
          })[0].outerHTML
       );
      $("table tbody").append(tr)
     })
   })
});

jsfiddle https://jsfiddle.net/11p7e3z6/