title: How to dynamically change Datatables multiple column headers using ajax and jquery without refreshing the webpage?
body: <p>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:</p>
  
  <pre><code>$( 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": '&lt;"top"iflp&lt;"clear"&gt;&gt;rt&lt;"bottom"iflp&lt;"clear"&gt;&gt;',
       "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);
          });
  }
  </code></pre>
  
  <p>Below is my HTML-table:</p>
  
  <pre><code>&lt;table id="table_id" class="display"&gt;
  &lt;thead&gt;
      &lt;tr id="titler"&gt;&lt;th&gt;Date&lt;/th&gt;&lt;th&gt;Actual&lt;/th&gt;
     &lt;th id="titleh"&gt;&lt;/th&gt;
      &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
      &lt;tr&gt;
          &lt;td&gt;Row 1 Data 1&lt;/td&gt;
          &lt;td&gt;Row 1 Data 2&lt;/td&gt;
      &lt;/tr&gt;
  
  &lt;/tbody&gt;
  &lt;/table&gt;
  </code></pre>
  
  <p>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):   </p>
  
  <pre><code> $(retitle).each(function(index, element){
             $('#titleh').html(element);
          });   
  </code></pre>
  
  <p>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.</p>
  
  <p>I haven been stuck for two days. Can anyone please help me?</p>
  
  <p>Many thanks!!!</p>
  
  <p>Katie</p>