skip to Main Content

I have a JSON array gathered from an AJAX response, as such [{"a":"dog","b":2,"c":3}, {"a":"cat","b":90,"c":4}]. I also have an HTML table as such:

<table id="reportTable">
   <thead>
      <tr>
          <th>a</th>
          <th>b</th>
          <th>c</th>
      </tr>
   </thead>
   <tbody>
      <tr>
          <td id="aValue"></td>
          <td id="bValue"></td>
          <td id="cValue"></td>
      <tr>
   </tbody>
</table>

I am trying to write the values of each JSON item to each <td> using the ID of each <td> tag, using jQuery. I have gotten the following so far, however I am now stuck and still cannot render anything inside the table:

$(document).ready(function () {
    $("form[name='table-update-form']").submit(function (event) {
        event.preventDefault();
        const formData = $(this).serialize();
        $.getJSON("/AJAX_response", formData, function (data) {

            var response = data.result;

            $.each(response, function (i, item) {
                $("#aValue").html(item.a);
                $("#bValue").html(item.b);
                $("#cValue").html(item.c);
            });
        });
    });
});

2

Answers


  1. As your response is JSON Array so you will have mutliple datas to add inside tr so use class instead of id and then generate tr inside your each loop and add that inside your tbody of table.

    Demo Code :

    /*$(document).ready(function() {
      $("form[name='table-update-form']").submit(function(event) {
        event.preventDefault();
        const formData = $(this).serialize();
        $.getJSON("/AJAX_response", formData, function(data) {*/
    
    var response = [{
      "a": "dog",
      "b": 2,
      "c": 3
    }, {
      "a": "cat",
      "b": 90,
      "c": 4
    }];
    var html = "";
    $.each(response, function(i, item) {
      //append tr inside html variable with values...
      html += `<tr>
          <td class="aValue">${item.a}</td>
          <td class="bValue">${item.b}</td>
          <td class="cValue">${item.c}</td>
          <tr>`
    });
    $("#reportTable tbody").html(html) //add final htmls inside tbody
    
    /* });
      });
    });*/
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <table id="reportTable">
      <thead>
        <tr>
          <th>a
          </th>
          <th>b
          </th>
          <th>c </th>
        </tr>
      </thead>
      <tbody>
      </tbody>
    </table>
    Login or Signup to reply.
  2. Firstly note that there are some issues with your HTML. The th need closing tags, but the main issue is that you’ve set id attributes on the td cells which implies that these can only exist once in the DOM.

    To iterate through your array of objects you will need to create multiple new rows. As such I would suggest you create a hidden ‘template’ row in the tfoot of the table which is cloned for each object in your array. From there you can place data attributes on the cells to be used to match the cell to the property of each object so that the value can be injected in to it.

    With that said, try this:

    // In the AJAX callback...
    var response = [{"a":"dog","b":2,"c":3}, {"a":"cat","b":90,"c":4}]
    
    let rows = response.map(obj => {
      let $tr = $('tfoot tr').clone();  
      Object.keys(obj).forEach(key => $tr.find(`td[data-key="${key}"]`).text(obj[key]));
      return $tr;
    })
    $('#reportTable').append(rows);
    tfoot { display: none; }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <table id="reportTable">
      <thead>
        <tr>
          <th>a</th>
          <th>b</th>
          <th>c</th>
        </tr>
      </thead>
      <tbody>
      </tbody>
      <tfoot>
        <tr>
          <td data-key="a"></td>
          <td data-key="b"></td>
          <td data-key="c"></td>
        </tr>  
      </tfoot>
    </table>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search