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
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 yourtbody
of table.Demo Code :
Firstly note that there are some issues with your HTML. The
th
need closing tags, but the main issue is that you’ve setid
attributes on thetd
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 placedata
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: