An ajax response is returning json object and I want to construct a table from. The json contain the column headers in an array and the actual data in another array of dictionaries. I want the table columns to be ordered according to the array of headers:
{
"columns": ["id", "category"],
"data":[
{"category": "fruit","id": 1},
{"category": "diary","id": 2}
]
}
$(document).ready(function() {
$("#submit").click(function(event) {
$.ajax({
data: {
user: $('#user').val(),
},
type: 'POST',
dataType: "json",
url: '/process'
})
.done(function(response) {
if (response.error) {
alert('Error!');
}
else {
var html = '<table class="table table-bordered"><thead><tr>';
jQuery.each(response.columns, function(index, value) {
html += "<th>" + value + "</th>"
})
html += "</tr></thead><tbody><tr>"
jQuery.each(response.data, function(index, value) {
jQuery.each(response.columns, function(idx, col) {
html+="<td>" + value[col] + "</td>"
})
})
html+="</tr></tbody></table>"
$(resulttable).append(html);
}
});
event.preventDefault();
});
});
I'm getting a table like this:
id category
1 fruit 2 diary
instead of
id category
1 fruit
2 diary