DataTables doesn´t load data

DataTables doesn´t load data

Eduardo1973Eduardo1973 Posts: 2Questions: 1Answers: 0

Best regards

I'm getting started with DataTables and JavaScript and I'm implementing a DataTable in my project. But I can't get the data loaded into it. From what I understood from reading the manual I have my code as follows:

HTML:

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <meta http-equiv="x-ua-compatible" content="ie=edge">

  <title>InfoFarma Web</title>

  <!-- Font Awesome Icons -->
  <link rel="stylesheet" href="css/all.min.css">
  <!-- Theme style -->
  <link rel="stylesheet" href="css/adminlte.min.css">
  <!-- Google Font: Source Sans Pro -->
  <link href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:300,400,400i,700" rel="stylesheet">
  <!-- Datatables style -->
  <link rel="stylesheet" href="css/dataTables.bootstrap4.min.css">
</head>

<div class="container-fluid">
   <div class="row align-items-center" style="height:50px;">
      <button class="btn btn-primary" type="button" id="btnAgregar">Agregar</button>
   </div>

      <table id="tabla-usuarios" class="table table-striped table-hover" style="width:100%">
         <thead class="thead-dark">
            <tr>
            <th>Id</th>
            <th>Usuario</th>
            <th>DNI</th>
            <th>Tipo</th>
            <th>Local</th>
            <th>Acciones</th>
            </tr>
         </thead>
         <tbody id="lista-usuarios">
         <!-- /.aqui jquery inserta la lista -->
         </tbody>
      </table>

</div><!-- /.container-fluid -->

  <!-- REQUIRED SCRIPTS -->
  <!-- jQuery -->
  <script src="js/jquery-3.5.1.min.js"></script>
  <!-- Bootstrap 4 -->
  <script src="js/bootstrap.min.js"></script>
  <!-- Datatables js -->
  <script src="js/jquery.dataTables.min.js"></script>
  <script src="js/dataTables.bootstrap4.min.js"></script>
  <!-- AdminLTE App -->
  <script src="js/adminlte.min.js"></script>
  <!-- modul js -->
  <script src="js/usuarios.js"></script>

And so I have my Jquery:

$(document).ready(function() {

   let modo = '';
   console.log('jquery is working!');
   var ListData = GetUserList();
   var tabla_usuario = $('#tabla-usuarios').DataTable({
      "language": { "url": "//cdn.datatables.net/plug-ins/1.10.15/i18n/Spanish.json" },
      "data": ListData,
      "columns": [
         { "data": "id" },
         { "data": "nombre" },
         { "data": "dni" },
         { "data": "tipo" },
         { "data": "local" },
         {"defaultContent": "<button class='btnEditar btn btn-success' type='button'>Editar</button>&nbsp;&nbsp;<button class='btnBorrar btn btn-danger' type='button'>Borrar</button>"}
     ]
   });

   // Obtener lista de usuarios
   function GetUserList() {
      $.ajax({
         url: '../controlador/UsuarioController.php?accion=listar',
         type: 'GET',
         success: function(response) {
            const usuarios = JSON.parse(response);
            console.log(usuarios);  //<-aqui hago un console para ver lo que devuelve
            return usuarios;
         }
      });
      modo = '';
   }

And this is seen in the console that returns the "usuarios" variable:

0: {id: "1", nombre: "EDUARDO FLORES RIVAS", dni: "07490241", tipo: "1", local: "1"}
1: {id: "2", nombre: "CARLOS ALBERTO GONZALES PRADA", dni: "03252045", tipo: "2", local: "1"}
2: {id: "3", nombre: "ANA VALLADARES RAMOS", dni: "25243044", tipo: "2", local: "1"}
3: {id: "5", nombre: "TERESA PARRA RIOS", dni: "50253624", tipo: "2", local: "1"}
4: {id: "6", nombre: "ALBERTO MORI RUIZ", dni: "40817254", tipo: "2", local: "1"}
length: 5
__proto__: Array(0)

I'll appreciate any help with that. Also comments if it is the best way to perform this functionality.

Cordial greetings.

This question has an accepted answers - jump to answer

Answers

  • kthorngrenkthorngren Posts: 21,125Questions: 26Answers: 4,916
    Answer ✓

    Ajax is an async process. basically that means the page load isn't paused while the Ajax request is waiting for the response. In your case that means var ListData = GetUserList(); is not complete when you initialize Datatables in the next statement.

    One option is to move your Datatables initialization inside the Ajax success function.

    the other option is to remove "data": ListData, from the Datatables initialization and use rows.add() in the Ajax success function to add the data to the Datatable.

    Kevin

  • Eduardo1973Eduardo1973 Posts: 2Questions: 1Answers: 0

    Thanks a lot! Finnally the datatable loads, this is the correct code:

    $(document).ready(function() {
    
       let modo = '';
       console.log('jquery is working!');
    
       var tabla_usuarios = $('#tabla-usuarios').DataTable({
          "language": { "url": "//cdn.datatables.net/plug-ins/1.10.15/i18n/Spanish.json" },
          "columns": [
             { "data": "id" },
             { "data": "nombre" },
             { "data": "dni" },
             { "data": "tipo" },
             { "data": "local" },
             {"defaultContent": "<button class='btnEditar btn btn-success' type='button'>Editar</button>&nbsp;&nbsp;<button class='btnBorrar btn btn-danger' type='button'>Borrar</button>"}
         ]
       })
    
       GetUserList() ;
    
       // Obtener lista de usuarios
       function GetUserList() {
       return $.ajax({
            url: '../controlador/UsuarioController.php?accion=listar',
            type: 'GET',
            success: function(response) {
                const usuarios = JSON.parse(response);
                console.log(usuarios); //<-aqui hago un console para ver lo que devuelve
                usuarios.forEach(user => {
                   tabla_usuarios.row.add( {
                      "id": user.id,
                      "nombre": user.nombre,
                      "dni": user.dni,
                      "tipo": user.tipo,
                      "local": user.local
                   }).draw();
                });
            }
          });
       }
    

    And the input Search and order headers works properly.

    Have a nice day !

This discussion has been closed.