I am creating a datatable by fetching data from database using AJAX response.
I am getting the following JSON data:
[
{
"id": "11105",
"name": "Gummy Drop (iPhone, Free, ROW except CN, 72.3MB, w"
},
{
"id": "11107",
"name": "Gummy Drop (iPad, Free, ROW except CN, 72.3MB, w/ "
},
{
"id": "4274",
"name": "Z-Redirect Non-Targeted Traffic Dragon City Mobile"
},
{
"id": "6484",
"name": "Z-Redirect Non-Targeted Traffic Dragon City Mobile"
}
]
The issue is, I may not know what data will be coming from AJAX response.
So I am extracting the keys of the JSON array so as to create the header, in which I am successful in doing so.
Here is my code:
$('#load').click(function()
{
var v = $('#drp_v').val();
var cnt = $('#drp_cnt').val();
var ctg = $('#drp_ctg').val();
alert("version :"+v+" category :"+ctg+" country :"+cnt);
$.post("ajax.php",{'version':v,'category':ctg,'country':cnt,'func':'show_datatable'},
function(data)
{
var aColumns = [];
var columns = [];
for(var i = 0; i < data.length; i++)
{
if(i>0)
break;
keycolumns = Object.keys(data[i]);
for(j = 0; j < keycolumns.length; j++)
{
alert(keycolumns[j]);
if($.inArray(keycolumns[j],aColumns.sTitle)<=0)
{
aColumns.push({sTitle: keycolumns[j]}) //Checks if
columns.push(keycolumns[j]) //Checks if
}
}
}
var oTable = $('#jsontable').dataTable({
"columns":aColumns,
"sDom": 'T<"clear">lfrtip',
"oTableTools": {
"aButtons": [
{
"sExtends": "csv",
"sButtonText": "CSV",
}
]
}
});
oTable.fnClearTable();
for(var i = 0; i < data.length; i++)
{
for(var c = 0; c < columns.length; c++)
{
oTable.fnAddData([
data[i].columns[c]]);
}
}
},'json');
});
As you can see, var columns = [];
actually contains the key of the JSON array I am getting. So the value of var columns
is like this:
['id','name','description']
;
So if we assume that id, name and description are three keys, then instead of using this code:
for(var i = 0; i < data.length; i++)
{
oTable.fnAddData([
data[i].id,
data[i].name,
data[i].description]);
}
I have used this code
for(var i = 0; i < data.length; i++)
{
for(var c = 0; c < columns.length; c++)
{
oTable.fnAddData([
data[i].columns[c]]);
}
}
so that the data can be loaded as dynamic key values that are stored in var columns.
But I think I made some mistake. Where have I gone wrong?