Jquery Datatables

1

Good evening, I'm working with Jquery , extracting data from a database and creating a dynamic table with the data. That is, I perform a data extraction in a javascript function:

var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", $urlEnvio, false);
xmlhttp.setRequestHeader("accept" ,"application/json");
xmlhttp.setRequestHeader("content-type" ,"application/json");
xmlhttp.send($urlEnvio);


var resultado = xmlhttp.response;
var long = resultado.length;
var elementos =JSON.parse(resultado);

Next, I create a header of the table (it's the same as in the dataTables example):

$('#infoDonantes').append("<div class='panel-body'>"+
    "<table width='100%' class='table table-striped table-bordered table-hover' id='dataTables-example'>"+
      "<thead>"+
        "<tr role='row'>"+
          "<th class ='sorting_asc'>Numero de Historial</th>"+
          "<th class ='sorting_asc'>Nombre</th>"+
      "</thead>"+
    "<tbody>");

And finally I go through the data with a loop to print all the results:

for(var i = 0; i < elementos.count; i++){

    $('#dataTables-example').append("<tr class='odd gradeA'>"+
        "<tr class='odd gradeA'>"+
          "<td>"+elementos.historias[i].nh+"</td>"+
          "<td>"+elementos.historias[i].name+"</td>"+
        "</tr>");
}
  $('</tr> ').append("</tbody>"+
      "</table>"+
    "</div>"+
    "<script src='vendor/datatables/js/jquery.dataTables.min.js'></script>"+
    "<script src='vendor/datatables-plugins/dataTables.bootstrap.min.js'></script>"+
    "<script>"+
      "$(document).ready(function() {"+
        "$('#dataTables-example').DataTable({"+
          "responsive: true"+
        "});"+
      "});"
  );

The problem is that this effectively shows me the results without problems, but as a normal table, that is, the search and sorting effect of the dataTables plugin does not apply. In the example that comes in the plugin the following lines are the ones that start the characteristics of the table:

<script src="../vendor/datatables-plugins/dataTables.bootstrap.min.js"></script>
<script src="../vendor/datatables-responsive/dataTables.responsive.js"></script>

<!-- Custom Theme JavaScript -->
<script src="../dist/js/sb-admin-2.js"></script>

<!-- Page-Level Demo Scripts - Tables - Use for reference -->
<script>
$(document).ready(function() {
    $('#dataTables-example').DataTable({
        responsive: true
    });
});
</script>

But I do not know where to insert that fragment so that the plugin works correctly. I hope you have explained me well. I would appreciate a help because it brings me head.

    
asked by AntonioMP87 18.04.2017 в 01:02
source

2 answers

0

The problem is rooted in the implementation of the plugin, you are currently including with jquery the reference to the plugin when you are loading the data, if you have already loaded this above it is not necessary to include it in the dynamic part.

Imagining that you do not have access to the html to include the code referring to the table you can not refer to an element that does not exist in the DOM, in that case you should call it in the following way.

$('#infoDonantes table').dataTable();

If you have access to the html to establish the structure of the table and only embed the new rows I would recommend you to do that separation of the code, it will be better reading.

    
answered by 18.04.2017 в 05:49
0

First of all you need to close the label <tr> of <thead>

Your problem is that you are concatenating the scripts of datatables incorrectly, that is:

In this passage, you are concatenating html to DOM but the call is not made to the scripts of the plugin, therefore you do not have the script loaded

$('</tr> ').append("</tbody>"+
    "</table>"+
  "</div>"+
  "<script src='vendor/datatables/js/jquery.dataTables.min.js'></script>"+
  "<script src='vendor/datatables-plugins/dataTables.bootstrap.min.js'></script>"+
  "<script>"+
    "$(document).ready(function() {"+
      "$('#dataTables-example').DataTable({"+
        "responsive: true"+
      "});"+
    "});"
);

The best thing is to eliminate that .append() and in the first one to leave it in this menra:

$('#infoDonantes').append("<div class='panel-body'>"+
  "<table width='100%' class='table table-striped table-bordered table-hover' id='dataTables-example'>"+
    "<thead>"+
      "<tr role='row'>"+
        "<th class ='sorting_asc'>Numero de Historial</th>"+
        "<th class ='sorting_asc'>Nombre</th>"+
      "</tr>"+
    "</thead>"+
    "<tbody>"+
    "</tbody>"+
  "</table>"+
"</div>");

First it is better to leave the scripts loaded on the page in this way:

<body>
<!-- Contenido de la pagina -->
...

<!-- script de la función de llenado de la tabla -->
...

<!-- Scripts cargados al inicio de la pagina -->
<script src="../vendor/datatables-plugins/dataTables.bootstrap.min.js"></script>
<script src="../vendor/datatables-responsive/dataTables.responsive.js"></script>
<!-- Custom Theme JavaScript -->
<script src="../dist/js/sb-admin-2.js"></script>

<!-- Page-Level Demo Scripts - Tables - Use for reference -->
<script>
$(document).ready(function() {
    $('#dataTables-example').DataTable({
        responsive: true
    });
});
</script>
</body>

because your table does not exist even in DOM this code snippet will not work, so that it works you must have at least the <table> tags declared in the DOM

<script>
  $(document).ready(function() {
    $('#dataTables-example').DataTable({
        responsive: true
    });
  });
</script>

Or apply the plugin dynamically in this way:

//funcion que se llama para cargar la información de la tabla
function cargarTabla(){
  //me imagino que aquí haces la peticion ajax para los datos
  //aquí concatenas la tabla a $('#infoDonantes')
  //llenando el cuerpo de la tabla
  for(var i = 0; i < elementos.count; i++){
    $('#infoDonantes').find('#dataTables-example').append(""+
       "<tr>"+
          "<td>"+elementos.historias[i].nh+"</td>"+
          "<td>"+elementos.historias[i].name+"</td>"+
       "</tr>");
  }

  $('#infoDonantes').find('#dataTables-example').DataTable({
        responsive: true,
        //destruir tablas viejas y aplicar a esta nueva con este selector $('#infoDonantes')
        destry: true //esto es para evitar un error de duplicidad a una tabla
    });
}
    
answered by 18.04.2017 в 21:25