How to pass parameters to ajax for using datatables plugin

How to pass parameters to ajax for using datatables plugin

easr01easr01 Posts: 10Questions: 1Answers: 0
edited January 15 in Free community support

Have an HTML table deployed through the DataTables plugin that works well when deployed from static data, retrieved through ajax from a MySQL database:

HTML:

                <div class="-body">
                    <table class="table table-bordered table-striped dt-responsive tablaFact02VFD" width="100%">
                        <thead>
                            <tr>
                                <th style="width: 10px;">#</th>
                                <th>Foto</th>
                                <th>Referencia</th>
                                <th>Descripción</th>
                                <th>Categoría</th>
                                <th>Stock</th>
                                <th>Cantidad</th>
                                <th>Precio</th>
                                <th>Impuestos</th>
                                <th>Acciones</th>
                            </tr>
                        </thead>
                    </table>
                </div>

AJAX:

  class TablaVentas{
    /* Mostrando la tabla productos */
    public $deFac;
    public function mostrarProductosFacturados(){
      $deFac= $this -> deFac;
      $Dataset = ModeloVentas::mdlMostrarProductosFacturados($deFac);
      $datosJson='{
        "data": [';
      for($i=0; $i < count($Dataset); $i++){
        
    ...

     ],';
      }
      $datosJson = substr($datosJson, 0, -1);
      $datosJson .= ']}';
      echo $datosJson;
    } 
  }

  /* Llamando a la tabla produtos */

 if(isset($_POST["deFac"])){
  $activarVFD = new TablaVentas();
  $activarVFD -> deFac = $_POST["deFac"];
  $activarVFD -> mostrarProductosFacturados();
}

JavaScript (something.js)
How to insert this:

        var deFac = $(this).val();
        var datos = new FormData();
        datos.append("deFac",deFac);
        $.ajax({
            url: "ajax/ventas.ajax.php",
            method: "POST",
            data: datos,

Here:

    $('.tablaFact02VFD').DataTable({
        "ajax": "ajax/datatable-ven-cli.ajax.php",
        "deferRender": true,
        "retrieve": true,
        "processing": true,
        })

I'm kinda self-tought programmer and I'm struggling with this issue.

Your help shall be truly appreciated

Edited by Allan - Syntax highlighting. Details on how to highlight code using markdown can be found in this guide.

Answers

  • easr01easr01 Posts: 10Questions: 1Answers: 0

    When $Dataset = ModeloVentas::mdlMostrarProductosFacturados($deFac); is given a static value for $deFac, the form goes well and the data is DataTables plugin goes well.
    I don't know how to pass the value through the plugin to ajax.

    Please help.

  • easr01easr01 Posts: 10Questions: 1Answers: 0

    Where says:
    $.ajax({
    url: "ajax/ventas.ajax.php",

    should say:
    $.ajax({
    url: "ajax/datatable-ven-cli.ajax.php",

    Ooops!

  • kthorngrenkthorngren Posts: 21,330Questions: 26Answers: 4,951

    Use ajax.data to pass parameters in the Datatables ajax request.

    Kevin

  • easr01easr01 Posts: 10Questions: 1Answers: 0

    Still stuck inside the tunnel:
    Following my thread, I'm working on a POS program and designing the sales form. As you will see, the form has two panels, one with the data that's being entered, left, and one for some different information to be presented to the clerk doing the invoice, right.
    The form has some data entered and is ready to be posted;
    this is the form before pressing the button "Guardar"

    This is the code for the field "Factura":

                      <div class="input-group">
                        <span class="input-group-addon"><i class="fa fa-key"></i> Factura: </span>
                        <?php
                          $dataset = ControladorVentas::ctrMostrarUltFac();
                          echo '<input type="text" class="form-control" id="rfFac" name="rfFac" value="'.$dataset["max_fac"].'" width="50%" readonly>'
                        ?>
                        <span class="input-group-addon"><i class="fa fa-calendar"></i> Fecha: </span>
                        <?php
                          date_default_timezone_set('America/Caracas');
                          $fech = date('d/m/Y');
                          echo '<input type="text" class="form-control" id="rfFec" name="rfFec" value="'.$fech.'" width="50%" readonly>'
                        ?>
                      </div>
    

    Please, note the field id rfFac.

    This is the code for the button:

        <button type="button" class="btn btn-primary btn-DetFac">Guardar</button>
    

    this is the code that corresponds to the right pane:

        <div class="col-lg-7 hidden-md hidden-sm hidden-xs">
          <div class="box box-warning">
            <div class="box-header with-border">
              <h2 class="title">Detalle de Compra</h2>
            </div>
              <div class="box-body">
                <form role="form" enctype="multipart/form-data" method="POST">
                  <div class="header" style="background:#3c8dbc; color: white ">
                  </div>
                  <div class="body">
                    <div class="uTility">
                    </div>
                  </div>
                </form>
              </div>
          </div>
    

    This is the JavaScript code for the button:

    $(document).on("click", ".btn-DetFac",function(){
      $(".uTility").empty();
      $(".uTility").append( 
        '<table class="table table-bordered table-striped dt-responsive tablaFact02VFD" width="100%">'+
          '<thead>'+
            '<tr>'+
              '<th style="width: 10px;">#</th>'+
              '<th>Imagen</th>'+
              '<th>Referencia</th>'+
              '<th>Descripcion</th>'+
              '<th>Categoria</th>'+
              '<th>Cantidad</th>'+
              '<th>Precio</th>'+
              '<th>Impuestos</th>'+
              '<th>Descuento</th>'+
            '</tr>'+
          '</thead>'+
        '</table>'
      );
    })
    

    This is the right pane on the form, after pressing the button "Guardar":

    this is the DataTables code that should be fired after the .tablaFact02VFD class table is deployed, as seen in the image:

    I intend to drag the rfFac value of the field and send it to Ajax, as I've described in the past comment, to activate the DataTables plugin and deploy the result table

    $('.tablaFact02VFD').DataTable({
        "ajax": {
          "url": "ajax/datatable-ven-cli.ajax.php",
          "type": "POST",
          "data":  function(){
            var deFac = $("#rfFac").val();
            var datos = new FormData();
            datos.append("deFac",deFac);
          },
        "deferRender": true,
        "retrieve": true,
        "processing": true,
        "language": {
          "sProcessing":     "Procesando...",
          "sLengthMenu":     "Mostrar _MENU_ registros",
          "sZeroRecords":    "No se encontraron resultados",
          "sEmptyTable":     "Ningún dato disponible en esta tabla",
          "sInfo":           "Mostrando registros del _START_ al _END_ de un total de _TOTAL_",
          "sInfoEmpty":      "Mostrando registros del 0 al 0 de un total de 0",
          "sInfoFiltered":   "(filtrado de un total de _MAX_ registros)",
          "sInfoPostFix":    "",
          "sSearch":         "Buscar:",
          "sUrl":            "",
          "sInfoThousands":  ",",
          "sLoadingRecords": "Cargando...",
          "oPaginate": {
            "sFirst":    "Primero",
            "sLast":     "Último",
            "sNext":     "Siguiente",
            "sPrevious": "Anterior"
            },
          "oAria": {
            "sSortAscending":  ": Activar para ordenar la columna de manera ascendente",
            "sSortDescending": ": Activar para ordenar la columna de manera descendente"
            }
          }
        }
      })
    

    But, NOTHING happens!!!

    What am I doing wrong?

  • allanallan Posts: 63,498Questions: 1Answers: 10,471 Site admin

    At the end of your button click function, after you've inserted the HTML for the table, I would expect to see a function call or something to initialise the DataTable there.

    It isn't clear to me where the DataTable is currently being initialised in the sequence of events. I would guess it is happening before the table has been inserted into the document.

    I would need a link to a test case to be able to say for sure.

    Allan

  • easr01easr01 Posts: 10Questions: 1Answers: 0

    As far as I've been interacting with the DataTables plugin, it should be fired by the class $('.tablaFact02VFD')

    This is the html

    <

    table class="table table-bordered table-striped dt-responsive tablaFact02VFD" width="100%">

    and this is the "trigger" in the ventas.js file:

    $('.tablaFact02VFD').DataTable...

  • easr01easr01 Posts: 10Questions: 1Answers: 0

    I've tried to markdown but, seeing the results, I preferred to leave it as plain text :blush:

  • kthorngrenkthorngren Posts: 21,330Questions: 26Answers: 4,951

    As Allan said we need to understand your code flow. It sounds like the code to initialized Datatables is not executed or executed before the HTML table is added. Based on your screenshots the default Datatables elements, like search, page length and paging buttons aren't displayed. Possibly you need to move the initialization at the end of the $(document).on("click", ".btn-DetFac",function(){ click event, after the table is inserted.

    Kevin

  • easr01easr01 Posts: 10Questions: 1Answers: 0

    Dear allan and kthorngren.

    I will try to set a complete storyboard into a file that will be put in my OneDrive and then share a link to it with you so, that way, I'll try to clarify what I'm doing and what I want to do.

    Right now it is 00:11 and I'm running on fumes

  • kthorngrenkthorngren Posts: 21,330Questions: 26Answers: 4,951

    Did you try moving the Datatables initialization code after inserting the table in the click event? If the table is not in the document when the Datatable is initialized the selector .tablaFact02VFD won't find any elements for Datatables to initialize so it won't work.

    Kevin

  • easr01easr01 Posts: 10Questions: 1Answers: 0

    Sorry for the delay.
    I was in other assignments and this is a personal grow project.

    Retaking.

    Thank you Kevin for your advice. I kinda got into it without knowing, because I hadn't read the thread till now.

    First I'm making a sales application as you can see:

    This is the way the form looks just before pressing the GUARDAR button (the upper blue one); this button fires this procedures:

    /* Procedure to Register the sale */

    $(document).on("click", ".CDF",function(){
    var dfFac = $("#rfFac").val();
    var dfRef = $("#dfRef").val();
    var dfCan = parseInt($("#dfCan").val());
    var dfPre = parseFloat($("#dfPre").val());
    var dfDct = parseFloat($("#dfDct").val());
    var datos = new FormData();
    datos.append("dffac",dfFac);
    datos.append("dfRef",dfRef);
    datos.append("dfcan",dfCan);
    datos.append("dfpre",dfPre);
    datos.append("dfdct",dfDct);
    //console.log("Datos: ",datos.get("dffac"));
    $.ajax({
    url: "ajax/ventas.ajax.php",
    method: "POST",
    data: datos,
    cache: false,
    contentType: false,
    processData: false,
    dataType: "json",
    success: function (dataset){
    if(dataset["sw"] == 0){
    Muestra_Fac();
    limpiaDetalle();
    }
    }
    })
    })

    This one fires Muestra_Fac():

    /* Shows the invoice progress on the right pannel */
    function Muestra_Fac(){
    $(".uTility").empty();
    $(".uTility").append(
    '

    '+ ''+ ''+ ''+ ''+ ''+ ''+ ''+ ''+ ''+ ''+ ''+ ''+ ''+ '
    #ImagenReferenciaDescripcionCategoriaCantidadPrecioImpuestosDescuento

    '
    );

    /* Right here I'm not depending on the class .tablaFact02VFD to fire the plunging, as I was been doing through the whole application, I'm kinda 'forcing' it ;) */

    /Here is where I suspect my error lies, but I'm confused/

    $('.tablaFact02VFD').DataTable({
      "ajax": {
        "url": "ajax/datatable-ven-prod.ajax.php",
        "type": "POST",
        "data":  function(){
          var deFac = $("#rfFac").val();
          var datos = new FormData();
          datos.append("DEFAC",deFac);
          console.log("DEFAC: ",datos.get("DEFAC"));
        }
      },
      "deferRender": true,
      "retrieve": true,
      "processing": true,
      "language": {
      "sProcessing":     "Procesando...",
      "sLengthMenu":     "Mostrar _MENU_ registros",
      "sZeroRecords":    "No se encontraron resultados",
      "sEmptyTable":     "Ningún dato disponible en esta tabla",
      "sInfo":           "Mostrando registros del _START_ al _END_ de un total de _TOTAL_",
      "sInfoEmpty":      "Mostrando registros del 0 al 0 de un total de 0",
      "sInfoFiltered":   "(filtrado de un total de _MAX_ registros)",
      "sInfoPostFix":    "",
      "sSearch":         "Buscar:",
      "sUrl":            "",
      "sInfoThousands":  ",",
      "sLoadingRecords": "Cargando...",
      "oPaginate": {
        "sFirst":    "Primero",
        "sLast":     "Último",
        "sNext":     "Siguiente",
        "sPrevious": "Anterior"
        },
      "oAria": {
        "sSortAscending":  ": Activar para ordenar la columna de manera ascendente",
        "sSortDescending": ": Activar para ordenar la columna de manera descendente"
        }
      }
    })
    

    }

    This JS procedure, effectively calls for: ajax/datatable-ven-prod.ajax.php, as you might see:

    but it sends nothing to the ajax procedure, as evidenced in the absence of the payload column on the screenshot

    This is the ajax procedure:

    <?php
    require_once "../controladores/ventas.controlador.php";
    require_once "../controladores/productos.controlador.php";

    require_once "../modelos/ventas.modelo.php";
    require_once "../modelos/productos.modelo.php";

    class TablaVentas{
    /* Mostrando la tabla de ventas */
    public $deFac;
    public function mostrarProductosFacturados(){
    $deFac= $this -> deFac;
    $Dataset = ModeloVentas::mdlMostrarProductosFacturados($deFac);
    $datosJson='{
    "data": [';
    for($i=0; $i < count($Dataset); $i++){
    if($Dataset[$i]["p_imagen"] && !empty(trim($Dataset[$i]["p_imagen"]))){
    $imagen = "<img src='".$Dataset[$i]['p_imagen']."' width='40px'>";
    }else{
    $imagen = "<img src='vistas/img/Productos/default/anonymous.png' width='40px'>";
    }
    $botones="

    ";
    $item = $i + 1;
    $referencia = $Dataset[$i]["df_referencia"];
    $descripcion = $Dataset[$i]["p_descripcion"];
    $categoria = $Dataset["cat_nombre"];
    $cantidad = $Dataset[$i]["df_cantidad"];
    /*
    $stock = $Dataset[$i]['p_stock'];
    if($stock < $demanda){
    $stock = "<button class='btn btn-danger'>$stock</button>";
    }elseif($stock >= $demanda && $stock <= $demanda * 2){
    $stock = "<button class='btn btn-warning'>$stock</button>";
    }else{
    $stock = "<button class='btn btn-success'>$stock</button>";
    }
    */
    $precio = $Dataset[$i]["df_precio"];
    $impuestos = $Dataset[$i]["impuestos"];
    $descuento = $Dataset[$i]["df_descuento"];
    $datosJson .='[
    "'.$item.'",
    "'.$imagen.'",
    "'.$referencia.'",
    "'.$descripcion.'",
    "'.$categoria.'",
    "'.$cantidad.'",
    "'.$precio.'",
    "'.$impuestos.'",
    "'.$descuento.'",
    "'.$botones.'"
    ],';
    }
    $datosJson = substr($datosJson, 0, -1);
    $datosJson .= ']}';
    echo $datosJson;
    }
    }

    /* Llamando a la tabla produtos */

    if(isset($_POST["DEFAC"])){
    $activarVFD = new TablaVentas();
    $activarVFD -> deFac = $_POST["DEFAC"];
    $activarVFD -> mostrarProductosFacturados();
    }

    this is the data this procedure calls:

    And finally, this is the response I have after all these:

    My apologies for the extra-long thread but, I couldn't find an easier way to explain it to you.

    Hope it gives you enough information to let you help me.

    Best regards.

  • kthorngrenkthorngren Posts: 21,330Questions: 26Answers: 4,951

    Take a look at the examples in the ajax.data docs and this example (you don't need to enable serverSide: true) for how to use ajax.data as a function. You need something like this:

      "ajax": {
        "url": "ajax/datatable-ven-prod.ajax.php",
        "type": "POST",
        "data":  function( datos ){
          datos.DEFAC = $("#rfFac").val();
        }
      },
    

    Follow the steps at the link in the Invalid JSON Response error to start troubleshooting:
    https://datatables.net/manual/tech-notes/1

    Let us know what you find in the response.

    I'm not familiar with PHP but I don't think you are encoding the response as JSON. See this tutorial.

    Kevin

  • easr01easr01 Posts: 10Questions: 1Answers: 0

    Hello Kevin and thanks for your diligence.

    I've already done this -sort of-

    Thank you, Kevin!!!

  • easr01easr01 Posts: 10Questions: 1Answers: 0

    It worked!!!

    Thank you all

Sign In or Register to comment.