I would like the Html table to reflect the same column order as shown in the json. I am expecting this...
Company, 2007, 2008, 2009
This is the json response in data.d
[{"Company":"ABC Infotech","2007":"3","2008":"3","2009":"4"},{"Company":"TPS Software","2007":"6","2008":"8","2009":"6"},{"Company":"XYZ InfoSystem","2007":"1","2008":"3","2009":"6"}]
The function to create the Html table returns a column order as this...
2007, 2008, 2009, Company
The following script returns the json perfectly. I have tried various json to html table scripts and when converted via eval or JSON.parse they seem to be sorting the column names?
Is there a fix?
$(document).ready(function () {
//the div in the page...
//<div id="output"style="margin: 10px;"></div>
$.makeTable = function (mydata) {
var table = $('<table class="table table-striped table-bordered" >');
var tblHeader = "<tr>";
for (var k in mydata[0]) tblHeader += "<th>" + k + "</th>";
tblHeader += "</tr>";
$(tblHeader).appendTo(table);
$.each(mydata, function (index, value) {
var TableRow = "<tr>";
$.each(value, function (key, val) {
TableRow += "<td>" + val + "</td>";
});
TableRow += "</tr>";
$(table).append(TableRow);
});
return ($(table));
};
return_pivot();
function return_pivot() {
//get file count
var jsonText = JSON.stringify({
new_file: "DataForPivot.xls",
row_field: "Company",
data_field: "CTC",
column_fields: "Year"
});
$.ajax({
type: "POST",
url: "Pivot.aspx/pivot",
data: jsonText,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
if (data.d != "0") {
console.log(data.d)
var mydata = eval(data.d);
var table = $.makeTable(mydata);
$(table).appendTo("#output");
}
}
}); //end ajax call
}
});