My attempt to dynamically build an HTML table was futile. Code works, but it doesn't output exactly what I need. There are only 2 properties within my JSON output: location and completed_on Instead of getting this:
+-------------------+---------------------+ | Location | Completed on | +-------------------+---------------------+ | 10 Duskwood Dr. | 2015-07-06 14:10:42 | | 2 Booty Bay Blvd. | 2015-07-09 13:44:38 | +-------------------+---------------------+ Code shows this(no thead visible):
[ { " l o c a ... ] ... prints the whole JSON character by character inside many <td> tags... This is an example of a typical JSON data I have to work with:
[{"location":"10 Duskwood Dr.","completed_on":"2015-07-06 14:10:42"}, {"location":"2 Booty Bay Blvd.","completed_on":"2015-07-09 13:44:38"}] This is the table markup I have hard coded into HTML and update with JSON:
<table id="completed_locations" class="table table-striped"> <thead> <tr> <th>Location</th> <th>Completed on</th> </tr> </thead> <tbody> // JSON data goes here </tbody> </table> I use this code to build <tr> and <td>:
// this is called within success of ajax to build table var oldTable = document.getElementById('completed_locations'), newTable = oldTable.cloneNode(); for(var i = 0; i < output.length; i++){ var tr = document.createElement('tr'); for(var j = 0; j < output[i].length; j++){ var td = document.createElement('td'); td.appendChild(document.createTextNode(output[i][j])); tr.appendChild(td); } newTable.appendChild(tr); } oldTable.parentNode.replaceChild(newTable, oldTable);
<td>elements, which looks wrong if you have an array of objects, not an array of arrays.