Behseini Behseini - 2 years ago 84
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%">
<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>
<tbody> </tbody>

and js file is like

request.done(function(data) {

which the output in console looks like

enter image description here

these are the values to be place in the

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 Source

Try using $.each()

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


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download