I am trying to change the column number and header according to the return value of ajax, while the table data is updated using DataTables jquery plugin. Javascript and jQuery Code below:
$( document ).ready(function() {
$.ajax({
type:'POST',
url: 'readtitle.php', //this php contains the column header
success:function(re){
setTitle(re); // this function is used to set column header
}
});
var oTable = $('#table_id').dataTable({
"bPaginate": false,
"bProcessing": true,
"bLengthChange": true,
"bFilter": true,
"bRetrieve": true,
"bInfo": false,
"bAutoWidth": false,
"bServerSide": true,
"sDom": '<"top"iflp<"clear">>rt<"bottom"iflp<"clear">>',
"aLengthMenu": [[10, 25, 50, -1], [10, 25, 50, "All"]],
"sAjaxSource": './aadata.txt',
"aoColumnDefs": [
{"aTargets":[]}
]
});
}
function setTitle(re){
re = re.substring(0,re.length-1);
var retitle = re.split(","); // this retitle can be of length 3 to 6, depends on the data
$(retitle).each(function(index, element){
$('#titleh').html(element);
});
}
Below is my HTML-table:
<table id="table_id" class="display">
<thead>
<tr id="titler"><th>Date</th><th>Actual</th>
<th id="titleh"></th>
</tr>
</thead>
<tbody>
<tr>
<td>Row 1 Data 1</td>
<td>Row 1 Data 2</td>
</tr>
</tbody>
</table>
Because in the HTML, I set 3 header. If the return header is of length 3, it works fine. However, if the length changes, the function (possibly wrong):
$(retitle).each(function(index, element){
$('#titleh').html(element);
});
only returns the last element, which makes the table column number fixed to 3. I don't know how to increase the column header using a loop in jQuery.
I haven been stuck for two days. Can anyone please help me?
Many thanks!!!
Katie