My task is to develop an ajax dataTable that can handle a variety of data sources with different column names and data types. The challenge lies in the fact that I cannot predefine the column names or data types when coding the dataTable, as each data source varies. However, all data sources share a common row_id
identity column which is used to retrieve individual records.
I have made numerous attempts but have not achieved success yet.
Examples of tables in the database:
Table A: https://i.sstatic.net/hiVhC.png
Table B: https://i.sstatic.net/PqY5H.png
Details HTML:
<table id="tblDetails" class="tbl"></table>
Details Controller:
public ActionResult GetDetails(int row_id, string table)
{
DataTable dt = new DataTable();
dt = helper.GetDetails(row_id, table);
JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
Dictionary<string, object> row;
if (dt.Rows.Count > 0)
{
foreach (DataRow dr in dt.Rows)
{
row = new Dictionary<string, object>();
foreach (DataColumn col in dt.Columns)
{
row.Add(col.ColumnName, dr[col]);
}
rows.Add(row);
}
}
return Json(rows, JsonRequestBehavior.AllowGet);
}
js:
var objParams = { 'table': table, 'row_id': row_id };
$.ajax({
url: $("#GetDetailsUrl").val(),
method: "post",
data: JSON.stringify(objParams),
dataType: 'json',
contentType: "application/json; charset=utf-8",
success: function (data) {
var key = Object.keys(data)[0];
var value = data[key];
Object.keys(data).forEach(function (key) {
console.log(key, value);
// Everything works fine until the next line of code
var row = '<tr><td>' + key + '</td><td> ' + value + '</td></tr>';
$('#tblDetails').append(row);
})
}
});
When querying tableB & row_id = 2, the `console.log(key, value);' produces the expected output: https://i.sstatic.net/PAWCm.png
However,
var row = '<tr><td>' + key + '</td><td> ' + value + '</td></tr>';
fails. It results in key = 0 and value = undefined.
What steps should I take to fix this issue and make key & value work in var row
just like it does when displayed in the console?