How to pass parameters to ajax for using datatables plugin
How to pass parameters to ajax for using datatables plugin
easr01
Posts: 10Questions: 1Answers: 0
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
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.
Where says:
$.ajax({
url: "ajax/ventas.ajax.php",
should say:
$.ajax({
url: "ajax/datatable-ven-cli.ajax.php",
Ooops!
Use
ajax.data
to pass parameters in the Datatablesajax
request.Kevin
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":
Please, note the field id rfFac.
This is the code for the button:
this is the code that corresponds to the right pane:
This is the JavaScript code for the button:
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
But, NOTHING happens!!!
What am I doing wrong?
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
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...
I've tried to markdown but, seeing the results, I preferred to leave it as plain text
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
Dear
allan
andkthorngren
.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
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
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(
'
'
);
/* 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/
}
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 screenshotThis 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.
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 useajax.data
as a function. You need something like this: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
Hello Kevin and thanks for your diligence.
I've already done this -sort of-
Thank you, Kevin!!!
It worked!!!
Thank you all