Problems with the DataTables plugin

0

I explain I'm doing a crud at the moment everything works well I followed a guide because I really do not have much knowledge and the guide did not have the dataTables plugin that I think is important in a CRUD but I add them and the modal is damaged but the tables do not appear and the truth is no longer where to put them this is the code without putting the plugin

<?php

require('../php/seguridad.php');
require_once('../php/Conexion.php');
$conn = Conectar();
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>.::Cerdos::.</title>

    <link href="../css/bootstrap.min.css" rel="stylesheet">
   <script type="text/javascript" src="../jscerdo/ajaxcer.js"></script>
</head>
<body>
  <nav class="navbar navbar-inverse">
    <div class="container">
      <div class="navbar-header">
        <a class="navbar-brand" href="/administrador/">Deseas Ir al Inicio?</a> 

 </nav>
    <div class="container">
      <div class="starter-template">
        <h1>.::Cerdos::.</h1>


        <button type="button" Onclick='Modal();' class="btn btn-primary btn-lg" >
          <span class="glyphicon glyphicon-star" aria-hidden="true"></span> Nuevo
        </button>

      </div>
      <div class="panel panel-default">
        <div class="panel-heading">.::Lista de Cerdos::.</div>
        <table id="table" class="display" cellspacing="0" width="100%">
          <thead>


            <tr>
              <th>#</th>
              <th>Cerdo</th>
              <th>Chapeta</th>
              <th>Raza</th>
              <th>Genero</th>
              <th>Modulo</th>
              <th>Corral</th>
         <th></th>

   <th></th>
            </tr>
          </thead>

          <tbody>



            <?php
              $sql = "SELECT * 
                  FROM cerdo cer 
                  INNER JOIN raza raz ON raz.id_raza=cer.id_raza 
                  INNER JOIN genero gen ON gen.id_genero=cer.id_genero 
                  INNER JOIN corral cor ON cor.id_corral=cer.id_corral 
                  INNER JOIN modulo mdu ON mdu.id_modulo=cor.id_modulo 
                  ORDER BY cerdo";

            $stmt = $conn->prepare($sql);
            $result = $stmt->execute();
            $rows = $stmt->fetchAll(\PDO::FETCH_OBJ);
            foreach($rows as $row){
              ?>
              <tr>
                <td><?php print($row->id_cerdo); ?></td>
                <td><?php print($row->cerdo); ?></td>
                <td><?php print($row->chapeta); ?></td>
                <td><?php print($row->raza); ?></td>
                  <td><?php print($row->genero); ?></td>
                  <td><?php print($row->modulo); ?></td>           
                <td><?php print($row->corral); ?></td>
                <td>
                  <div class="btn-group">
                    <button type="button" class="btn btn-danger">Seleccione</button>
                    <button type="button" class="btn btn-danger dropdown-toggle" data-toggle="dropdown" aria-expanded="false">
                      <span class="caret"></span>
                    </button>
                    <ul class="dropdown-menu" role="menu">

                      <li><a onclick="Eliminar('<?php print($row->id_cerdo); ?>');">Eliminar</a></li>
                      <li><a onclick="Editar('<?php print($row->id_cerdo); ?>','<?php print($row->cerdo); ?>','<?php print($row->chapeta); ?>','<?php print($row->raza); ?>','<?php print($row->genero); ?>','<?php print($row->modulo); ?>','<?php print($row->corral); ?>');">Actualizar</a></li>
                    </ul>
                  </div>
                </td>
              </tr>
              <?php
            }
            ?>
          </tbody>
        </table>
      </div>

      <div class="modal fade" id="modal" tabindex="-1" role="dialog" aria-hidden="true">
        <div class="modal-dialog">
          <div class="modal-content">
            <div class="modal-header">
              <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
              <h4 class="modal-title">Nuevo Cerdo</h4>
            </div>

            <form role="form" action="" name="frmClientes" onsubmit="Registrar(idP,accion); return false">
              <div class="col-lg-12">
                <div class="form-group">
                  <label>Cerdo</label>
                  <input name="cerdo" class="form-control" required>
                </div>


                <div class="form-group">
                  <label>Chapeta</label>
                  <input name="chapeta" class="form-control" required>
                </div>

                <div class="form-group">
                  <label for="lll">Raza</label>
                 <select  id="lll" name="raza">
                  <?php


$sql = "SELECT * FROM raza ORDER BY raza";
$stmt =$conn->prepare($sql);
$result = $stmt->execute();
 $rows = $stmt->fetchAll(\PDO::FETCH_OBJ);
foreach ($rows as $row) {
  ?>
<option value ="<?php print($row->id_raza);?>"><?php print($row->raza);?></option>

<?php

}

?>
</select>
              </div>

                <div class="form-group">
                   <label for="lll">Genero</label>
                 <select  id="lll" name="genero">
         <?php


$sql = "SELECT * FROM genero ORDER BY genero";
$stmt =$conn->prepare($sql);
$result = $stmt->execute();
$rows = $stmt->fetchAll(\PDO::FETCH_OBJ);
foreach ($rows as $row) {
?>
<option value ="<?php print($row->id_genero);?>"><?php print($row->genero);?></option>

<?php
}
?>
</select>
                </div>

                 <div class="form-group">                

          <label for="lll">Modulo</label>
                 <select  id="lll" name="modulo">
         <?php


        $sql = "SELECT * FROM modulo ORDER BY modulo";

$stmt =$conn->prepare($sql);
$result = $stmt->execute();
$rows = $stmt->fetchAll(\PDO::FETCH_OBJ);
foreach ($rows as $row) {
  ?>
<option value ="<?php print($row->id_modulo);?>"><?php print($row->descripcion);?>"><?php print($row->modulo);?></option>

<?php
}
?>
</select>
 </div>

                <div class="form-group">
                  <label for="lll">Corral</label>
                 <select  id="lll" name="corral">
<?php
$sql = "SELECT * FROM corral ORDER BY corral";
$stmt =$conn->prepare($sql);
$result = $stmt->execute();
$rows = $stmt->fetchAll(\PDO::FETCH_OBJ);
foreach ($rows as $row) {
  ?>
<option value ="<?php print($row->id_corral);?>"><?php print($row->corral);?></option>

<?php
}
?>
      </select>
    </div>
</div>

                <button type="submit" class="btn btn-info btn-lg">
                  <span class="glyphicon glyphicon-star" aria-hidden="true"></span> Registrar
                </button>

              </div>
            </form>
            <div class="modal-footer">
              <button type="button" class="btn btn-danger btn-circle" data-dismiss="modal"><i class="fa fa-times"></i>x</button>
            </div>
          </div>
        </div>
      </div>

    </div>
    <script src="../js/jquery.min.js"></script>
    <script src="../js/bootstrap.min.js"></script>
    <script type="text/javascript">
    function Modal(){
    Nuevo();
        $('#modal').modal('show');
    }

    var accion;
    var idP;
    function Nuevo(){
      accion = 'N';
      document.frmClientes.cerdo.value = "";
      document.frmClientes.chapeta.value = "";
      document.frmClientes.raza.value = "";
      document.frmClientes.genero.value = "";
      document.frmClientes.modulo.value = "";
      document.frmClientes.corral.value = "";
      $('#modal').modal('show');
    }
    function Editar(id, cerdo, chapeta, raza, genero, modulo, corral ){
      accion = 'E';
      idP = id;
      alert(cerdo,chapeta,raza,genero,modulo,corral);
      document.frmClientes.cerdo.value = cerdo;
      document.frmClientes.chapeta.value = chapeta;
      document.frmClientes.raza.value = raza;
      document.frmClientes.genero.value = genero;
      document.frmClientes.modulo.value = modulo;
      document.frmClientes.corral.value = corral;
      $('#modal').modal('show');
    }


    </script>


  </body>

  </html>
    
asked by user90058 18.06.2018 в 09:13
source

2 answers

0

I was trying to reproduce some problem between both bookstores and I have not done anything wrong. I can advise you some things:

  • Be sure to import both the CSS and JS of jQuery.dataTables after importing jQuery, since jQuery.dataTables takes jQuery functions and if imported before it will not perform its functions correctly.

  
    <script src="../js/jquery.min.js"></script>
    <script src="../js/bootstrap.min.js"></script>
    <script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.10.18/js/jquery.dataTables.js"></script>
    <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.18/css/jquery.dataTables.css">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  • Add your scripts and styles in the section (before the document.
  • Be sure to initialize the dataTable:

<script type="text/javascript">
        $(document).ready(function () {
            $('#example').DataTable({
                columnDefs: [{
                    targets: [0],
                    orderData: [0, 1]
                }, {
                    targets: [1],
                    orderData: [1, 0]
                }, {
                    targets: [4],
                    orderData: [4, 0]
                }]
            });
        });
    </script>
* Add the CSS of Bootstrap.

I hope it has helped you, a hug.

    
answered by 18.06.2018 в 10:06
0

Your code is too complex because of the interpolation of html and php to debug. What I recommend is that you do all your queries to the DB at the beginning and print the result as JSON, so that from there down everything is done with JS variables.

For example, instead of:

      $sql = "SELECT * 
              FROM cerdo cer 
              INNER JOIN raza raz ON raz.id_raza=cer.id_raza 
              INNER JOIN genero gen ON gen.id_genero=cer.id_genero 
              INNER JOIN corral cor ON cor.id_corral=cer.id_corral 
              INNER JOIN modulo mdu ON mdu.id_modulo=cor.id_modulo 
              ORDER BY cerdo";

        $stmt = $conn->prepare($sql);
        $result = $stmt->execute();
        $rows = $stmt->fetchAll(\PDO::FETCH_OBJ);
        foreach($rows as $row){
          ?>
          <tr>
            <td><?php print($row->id_cerdo); ?></td>
            <td><?php print($row->cerdo); ?></td>
            <td><?php print($row->chapeta); ?></td>
            <td><?php print($row->raza); ?></td>
              <td><?php print($row->genero); ?></td>
              <td><?php print($row->modulo); ?></td>           
            <td><?php print($row->corral); ?></td>
            ...
         </tr>
         <?php } ?>
       </tbody>
     </table>

Do:

    $stmt = $conn->prepare($sql);
    $result = $stmt->execute();
    $rows = $stmt->fetchAll(\PDO::FETCH_ASSOC);
    echo 'var cerdos = JSON.parse('. json_encode($rows) .')';

And you will have the variable pigs defined as a javascript object, so that later you can fill the table by doing:

  cerdos.forEach(function (cerdo) {
    var tr = jQuery('<tr></tr>');
    jQuery('<td>' + cerdo.id_cerdo + '</td>').appendTo(tr);
    jQuery('<td>' + cerdo.cerdo + '</td>').appendTo(tr);
    jQuery('<td>' + cerdo.chapeta + '</td>').appendTo(tr);
    jQuery('<td>' + cerdo.raza + '</td>').appendTo(tr);
    var editar = $('<button type="button"  class="editar btn btn-xs btn-primary">Editar</button>');

    editar.data('cerdo', cerdo);
    btns = jQuery('<td></td>');
    btns.append(editar)
      .appendTo(tr);
    $('#table').find('tbody').append(tr);
  });
  $('#table').DataTable();

If you notice, the button to edit a pig does not have all the characteristics of this inline, but I added a data-attribute with the object "pig" so that later you can do:

  $('.editar').on('click', function () {
    var cerdo = $(this).data('cerdo');
    document.frmClientes.id_cerdo.value = cerdo.id_cerdo;
    document.frmClientes.cerdo.value = cerdo.cerdo;
    document.frmClientes.chapeta.value = cerdo.chapeta;
    document.frmClientes.raza.value = cerdo.raza;
    $('#modal').modal('show');
  });

I'll give you an example, of course I used the data from link that have employees instead of pigs, but to edit and list it looks pretty clear.

 var empleados = [{
      "id": 1,
      "name": "Garrett Winters",
      "position": "Accountant",
      "office": "Tokyo"
    }, {
      "id": 2,
      "name": "Ashton Cox",
      "position": "Junior Technical Author",
      "office": "San Francisco"
    }, {
      "id": 3,
      "name": "Cedric Kelly",
      "position": "Senior Javascript Developer",
      "office": "Edinburgh"
    }, {
      "id": 4,
      "name": "Airi Satou",
      "position": "Accountant",
      "office": "Tokyo"
    }, {
      "id": 5,
      "name": "Brielle Williamson",
      "position": "Integration Specialist",
      "office": "New York"
    }, {
      "id": 6,
      "name": "Herrod Chandler",
      "position": "Sales Assistant",
      "office": "San Francisco"
    }, {
      "id": 7,
      "name": "Rhona Davidson",
      "position": "Integration Specialist",
      "office": "Tokyo"
    }];

    var puestos = ["Accountant", "Junior Technical Author", "Senior Javascript Developer", "Integration Specialist", "Sales Assistant", "Javascript Developer", "Software Engineer", "Office Manager", "Support Lead", "Regional Director", "Senior Marketing Designer", "Marketing Designer", "Chief Financial Officer (CFO)", "Systems Administrator", "Personnel Lead", "Development Lead", "Chief Marketing Officer (CMO)", "Pre-Sales Support", "Chief Executive Officer (CEO)", "Developer", "Chief Operating Officer (COO)", "Regional Marketing"];
    var oficinas = ["Tokyo", "San Francisco", "Edinburgh", "New York", "London", "Sidney", "Singapore"];



    jQuery(document).ready(function() {


      empleados.forEach(function(empleado) {
        var tr = jQuery('<tr></tr>');
        jQuery('<td>' + empleado.id + '</td>').appendTo(tr);
        jQuery('<td>' + empleado.name + '</td>').appendTo(tr);
        jQuery('<td>' + empleado.position + '</td>').appendTo(tr);
        jQuery('<td>' + empleado.office + '</td>').appendTo(tr);
        var editar = $('<button type="button"  class="editar btn btn-xs btn-primary">Editar</button>');
        editar.data('empleado',empleado);
        btns = jQuery('<td></td>');
        btns.append(editar)
        .appendTo(tr);
        $('#table').find('tbody').append(tr);
      });
      $('#table').DataTable();
      
      puestos.forEach(function(puesto) {
        $('#puestos').append('<option value"'+puesto+'">'+puesto+'</option>');
      });
      
      oficinas.forEach(function(oficina) {
        $('#oficinas').append('<option value"'+oficina+'">'+oficina+'</option>');
      });

      $('.editar').on('click',function() {
        var empleado=$(this).data('empleado');
          console.log()
          document.frmClientes.id.value = empleado.id;
          document.frmClientes.nombre.value = empleado.name;
          document.frmClientes.oficina.value = empleado.office;
          document.frmClientes.puesto.value = empleado.position;
        $('#modal').modal('show');
      });
    });
    #table td {
      font-size: 12px;
    }
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.2/css/bootstrap.min.css" rel="stylesheet">
  <link href="https://cdn.datatables.net/1.10.18/css/jquery.dataTables.min.css" rel="stylesheet">
  <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.2/js/bootstrap.min.js"></script>
  <script src="https://cdn.datatables.net/1.10.18/js/jquery.dataTables.min.js"></script>
 
  <div class="container">
    <div class="starter-template">
      <h3>.::Empleados::.</h3>
    </div>
    <div class="panel panel-default">
      
      <div class="panel-heading">.::Lista de Empleados::.</div>
      <table id="table" class="display" cellspacing="0" width="100%">
        <thead>
          <tr>
            <th>ID</th>
            <th>Nombre</th>
            <th>Puesto</th>
            <th>Oficina</th>
            <th width="100px">Acciones</th>
          </tr>
        </thead>

        <tbody>

        </tbody>
      </table>
    </div>

    <div class="modal fade" id="modal" tabindex="-1" role="dialog" aria-hidden="true">
      <div class="modal-dialog">
        <div class="modal-content">
          <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
            <h4 class="modal-title">Editar empleado</h4>
          </div>

          <form role="form" action="" name="frmClientes" onsubmit="Registrar(idP,accion); return false">
            <div class="col-lg-12">
              <div class="form-group">
                <label>Id</label>
                <input name="id" id="id" class="form-control" required>
              </div>


              <div class="form-group">
                <label>Nombre</label>
                <input id="nombre" name="nombre" class="form-control" required>
              </div>

              <div class="form-group">
                <label for="puestos">Puesto</label>
                <select id="puestos" name="puesto">
                </select>
              </div>

              <div class="form-group">
                <label for="oficinas">Oficina</label>
                <select id="oficinas" name="oficina">
                </select>
              </div>

              <button type="submit" class="btn btn-info btn-lg">
                <span class="glyphicon glyphicon-star" aria-hidden="true"></span> Registrar
              </button>

            </div>
          </form>
          <div class="modal-footer">
            <button type="button" class="btn btn-danger btn-circle" data-dismiss="modal"><i class="fa fa-times"></i>x</button>
          </div>
        </div>
      </div>
    </div>
  </div>
    
answered by 18.06.2018 в 15:19