Datatable Error Can not read property 'mData' of undefined

1

I am showing the data from my Database in a table using javascript the data is displayed correctly, but the DataTable options are not being displayed. In the browser console I get this error

Uncaught TypeError: Cannot read property 'mData' of undefined
at HTMLTableCellElement.<anonymous> (datatables.js:1184)
at Function.each (jquery-3.2.1.min.js:2)
at r.fn.init.each (jquery-3.2.1.min.js:2)
at HTMLTableElement.<anonymous> (datatables.js:1181)
at Function.each (jquery-3.2.1.min.js:2)
at r.fn.init.each (jquery-3.2.1.min.js:2)
at r.fn.init.DataTable [as dataTable] (datatables.js:881)
at r.fn.init.$.fn.DataTable (datatables.js:15082)
at Object.success (pagos_tipos.js:14)
at i (jquery-3.2.1.min.js:2)

The data is shown by Javascript

 $.post(url+"C_Pagos_Tipos/getPagos",
 function(data){

 var obj = JSON.parse(data);
 $.each(obj, function(i, item){
 $("#tblPagos").append(
  '<tr>'+
  '<td>'+item.id+'</td>'+
  '<td>'+item.tipo_pago+'</td>'+
  '<td><a href="#" title="Editar" data-toggle="modal" data-target="#modalEditar" onClick="selPagos(\''+item.id+'\',\''+item.tipo_pago+'\');"><i style="color:#555;" ></i> Editar</a></td>'+
  '</tr>'
);
});
$("#tblPagos").DataTable({

'paging': true,
'info': true,
'filter': true

});
});

Edited: add the html

      <div class="table-responsive">
        <table class="table table-striped" id="tblPagos">
          <thead>
            <tr>
              <th>#Código</th>
              <th>Nombre</th>
            </tr>
          </thead>
          <tbody>
          </tbody>
        </table>

      </div>

At the end of the HTML

 <script type="text/javascript">
  var url = "<?php echo base_url(); ?>";
 </script>

 <script src="<?php echo base_url();?>assets/js/jquery-3.2.1.min.js"></script>

 <link rel="stylesheet" type="text/css" href="<?php echo base_url();?>assets/datatables/datatables.css">
 <script type="text/javascript" charset="utf8" src="<?php echo base_url();?>assets/datatables/datatables.js"></script>

 <script src="<?php echo base_url();?>assets/js/pagos_tipos.js"></script>

 <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css">
    
asked by CristianOx21 27.12.2017 в 23:31
source

1 answer

1

It's a pretty common mistake. Since the condition for a DataTable is that the number of rows in thead is equal to the tbody , it has only two in thead but adds an additional button to tbody therefore exceeds one the columns, then your error can be solved simply by adding a th empty at the end to equalize the columns.

    
answered by 28.12.2017 / 01:23
source