1

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

4
  • Hi if you run the setTitle('with what ever choice of header') in console window in the browser , is it giving desired ouput ? for me its giving Commented Feb 12, 2014 at 14:00
  • @CodingAnt Hi, thanks for replying. Indeed, it gives me the desired output. But since in the HTML table, the <th></th> number is fixed. I can't use html() function to simply add one header to it. Commented Feb 12, 2014 at 14:14
  • HI did it worked or what ?? Curious Commented Feb 14, 2014 at 7:01
  • Sorry for the late reply... please see my own answers below. Cheers! Commented Mar 28, 2015 at 23:39

3 Answers 3

3

I solved the question by changing the way of initialising table in HTML instead of altering the settings in Datatables.

What I did is: first, remove the existing table, as well as the table wrapper!

 $('#table_id').remove();
 $('#table_id_wrapper').remove();

Then initialise a new table. and set the format of header/body according to your data:

 var content = "<table id='table_id' class='display datatable' style='width:100%;'><thead>";
 content +='<tr>';


 re = re.substring(0,re.length-1);
 // alert(re);
 var retitle = re.split(",");
    alert (retitle + 'x');
   var c = retitle.length;
   var atarget = [];
   var stitle = [];
   for(var i=0; i<c; i++){
     atarget[i] = i;
     stitle[i] = retitle[i];
     content += '<td>' +retitle[i]  + '</td>';

   }

  content +=' </tr></thead>';
  content +='<tbody></tbody>'
  content += "</table>";

Then, append your table to your webpage. Here I attached it to my tab:

  $('#tab3').append(content);

Finally, I initialised the Datatable settings by changing the aoColumnDef according to my own data. Noted that the data format must match the way you previously define your HTML table

   var settings = {

     "bPaginate": false,
     "bProcessing": true,
    "bLengthChange": true,
    "bFilter": false,
    "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":atarget}
     ]
   };

 $('#table_id').dataTable().fnDestroy();
 $('#table_id').dataTable(settings);
 $('#table_id').dataTable().fnReloadAjax();

By the way, thank you @CodingAnt, @JerryDDG all the same for your help.

A related question about changing the Datatable title is solved here:

What is the right format to change Datatables column using array?

Sign up to request clarification or add additional context in comments.

Comments

1

Maybe you should destroy the old table and create a new one with the new config.

$(tableSelector)
    .dataTable(dataTable_setting)
    .fnAddData(data);

$.ajax({
    url: ...
    data: ...
    success: function(data) {
        if (columns number changed) {
            $(tableSelector).empty();
            $(tableSelector)
                .dataTable(newDataTable_setting)
                .fnAddData(newData);
        }
    }
})

Comments

0

I am not too sure about this , actually your requirement is still not clear to me .

In case its right , you need to little bit fine tune according to your requirement. Its adding header if needed.

<script type="text/javascript">

function setTitle(re){

    re = re.substring(0,re.length-1);

    var retitle = re.split(",");  

    //destroy element created  on request
    $('th').each(function(index, element)
    {

          if(index > 2)
          {
            $( this ).remove();
          }

    });


    //For extra header if any

    if(retitle.length > 1)
    {
        for (var i = 1; i <= retitle.length; i++) 
        {
            $('#titler').append('<th></th>');
        };

    }

    var counter     =   0;

    $('th').each(function(index, element)
    {

          if(index > 1)
          {
            $( this ).text(retitle[counter]);
            counter ++;
          }

    });

}


</script>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.