Search by Date and show data in BootstrapTable - php

What I want to do is to input some date time range and show me the data in a BootstrapTable. I am not able to do it.
I have two php files one is my WebSite and the other is the MySql query.
So this where I load the Input data fields and my BootstrapTabel:
<div class='col-md-2 float-left'>
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text">Datum von:</span>
</div>
<input id="dateVon" name="dateVon" value="2022-01-01" type="text" class="form-control" placeholder="2022-01-01" aria-describedby="dateVon">
</div>
</div>
<div class='col-md-2 float-left'>
<div class="input-group">
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text">Datum bis:</span>
</div>
<input id="dateBis" name="dateBis" value="2022-01-31" type="text" class="form-control" placeholder="2022-01-31" aria-describedby="dateBis">
</div>
</div>
</div>
<button id="remove" class="btn btn-danger btn-sm" data-toggle="modal" data-target="#deleteModal" disabled>
<i class="bi bi-trash"></i> Delete
</button>
<button id="refresh" class="btn btn-primary btn-sm" onclick="refreshFunction(dateVon,dateBis);">
<i class="bi bi-trash"></i> Refresh
</button>
</div>
<div class="card-body">
<table id="table"
data-toolbar="#table-responsive"
data-search="true"
data-show-refresh="true"
data-show-toggle="true"
data-show-fullscreen="true"
data-show-columns="true"
data-show-columns-toggle-all="true"
data-detail-view="true"
data-show-export="true"
data-click-to-select="true"
data-detail-formatter="detailFormatter"
data-minimum-count-columns="2"
data-pagination="true"
data-id-field="ID"
data-page-size="50"
data-page-list="[50, 100, all]"
data-show-footer="true"
data-side-pagination="client"
data-url="verpAnrufData.php"
data-response-handler="responseHandler"
data-detail-view="true">
</table>
<script>
var $table = $('#table')
var $remove = $('#remove')
var selections = []
function getIdSelections() {
return $.map($table.bootstrapTable('getSelections'), function(row) {
return row.ID
})
}
function responseHandler(res) {
$.each(res.rows, function(i, row) {
row.state = $.inArray(row.ID, selections) !== -1
})
return res
}
function totalTextFormatter(data) {
return 'Total'
}
function totalNameFormatter(data) {
return data.length
}
function totalPriceFormatter(data) {
var field = this.field
return '$' + data.map(function(row) {
return +row[field].substring(1)
}).reduce(function(sum, i) {
return sum + i
}, 0)
}
function initTable() {
$table.bootstrapTable('destroy').bootstrapTable({
locale: 'de-DE',
columns: [{
field: 'state',
checkbox: true,
rowspan: 1,
align: 'center',
valign: 'middle'
}, {
field: 'id',
title: 'ID',
rowspan: 1,
align: 'center',
valign: 'middle',
sortable: true,
footerFormatter: totalTextFormatter
}, {
field: 'name',
title: 'Kunde',
sortable: true,
align: 'left',
footerFormatter: totalNameFormatter
}, {
field: 'callerid',
title: 'Anrufer',
sortable: true,
align: 'left'
}, {
field: 'datetime_entry_queue',
title: 'DatumZeit',
sortable: true,
align: 'left'
}, {
field: 'duration_wait',
title: 'Warteschleife (sec)',
sortable: true,
align: 'left'
}]
})
$table.on('check.bs.table uncheck.bs.table ' +
'check-all.bs.table uncheck-all.bs.table',
function() {
$remove.prop('disabled', !$table.bootstrapTable('getSelections').length)
//$btnEdit.prop('disabled', !$table.bootstrapTable('getSelections').length)
// save your data, here just save the current page
selections = getIdSelections()
// push or splice the selections if you want to save all data selections
})
$table.on('all.bs.table', function(e, name, args) {
console.log(name, args)
})
}
$(function() {
initTable()
$('#locale').change(initTable)
})
function refreshFunction() {
var data = {
dateVon: $("input[id='dateVon']").val(),
dateBis: $("input[id='dateBis']").val()
};
$.ajax({
method: "post",
url: "verpAnrufData.php",
data: data,
success: function(response) {
/* console.log(data); */
/* params.success({
"rows": data,
"total": data.length
}, null, {}); */
//initTable();
$table.bootstrapTable('refresh')
}
})
}
and this is my MySql php file:
<?php
include "dbConn.php";
$dateVon = $_POST["dateVon"];
$dateBis = $_POST["dateBis"];
$sqltran = mysqli_query($db, "SELECT ce.id,
ce.callerid,
ce.datetime_entry_queue,
ce.duration_wait,
convert(cast(convert(cae.name using latin1) as binary) using utf8) name
FROM call_center.call_entry ce, call_center.campaign_entry cae
WHERE ce.id_campaign = cae.id
AND datetime_entry_queue BETWEEN '$dateVon 00:00:00' AND '$dateBis 23:59:59'
AND status = 'abandonada'
ORDER BY name, datetime_entry_queue ASC;");
$count = mysqli_num_rows($sqltran) ;
$arrVal = array();
$i=1;
while ($rowList = mysqli_fetch_array($sqltran)) {
$name = array(
'id' => $rowList['id'],
'name'=> $rowList['name'],
'callerid'=> $rowList['callerid'],
'datetime_entry_queue'=> $rowList['datetime_entry_queue'],
'duration_wait'=> $rowList['duration_wait'],
);
array_push($arrVal, $name);
$i++;
}
$allData = array(
'total' => $count,
'rows' => $arrVal,
);
echo json_encode($allData);
mysqli_close($db); // close connection
If i harde code the Dates in this file like this:
$dateVon = "2022-01-01";
$dateBis = "2022-12-31";
Then I can see the data, but then I am not able to input another dates and refresh it.
I am desperate I can not make it work, pls help. :)

I have found the answer of my problem, it was in the ajax function and the way I was responding the cell. Thx KIKO Software for the sugesstion.
function refreshFunction() {
$.ajax({
method: "POST",
dataType: "json",
url: "verpAnrufData.php",
data: {
dateVon: $("input[id='dateVon']").val(),
dateBis: $("input[id='dateBis']").val()
},
success: function(response) {
console.log(response);
$table.bootstrapTable('load',{
"rows": response,
"total": response.length
}, null, {});
}
})
};

Related

save arrays in mysql with php and reactj

I have a form in reactjs that saves a variable "name" and two dynamic arrays, one is called "data1" and "data2", each array can contain several values ​​since I can add more dynamic values ​​from reactjs to there, but not I have been able to pass those values ​​of the array that are saved in mysql from the php since it only saves the name and the first two data of the array of data1 and data2:
https://codesandbox.io/s/ecstatic-browser-nvcee?file=/src/App.js:0-8794
I need to be able to save the complete arrays "data1" and data2 in the database.
reactjs
import React, {useState} from 'react';
import axios from 'axios';
import {
Grid,
Table,
TableBody,
TableCell,
TableContainer,
TableHead,
TableRow,
Paper
} from "#material-ui/core";
import AddCircleOutlineIcon from "#material-ui/icons/AddCircleOutline";
import { withStyles, makeStyles } from "#material-ui/core/styles";
import DeleteIcon from "#material-ui/icons/Delete";
const StyledTableRow = withStyles((theme) => ({
root: {
"&:nth-of-type(odd)": {
backgroundColor: theme.palette.action.hover
}
}
}))(TableRow);
/*const useStyles = makeStyles((theme) => ({
paper: {
display: "flex",
flexDirection: "column",
padding: "30px 40px",
marginTop: "50px",
marginLeft: "20px",
marginRight: "20px"
},
heading: {
paddingLeft: "10px"
},
label: {
lineHeight: "2",
fontSize: "14px"
},
input: {
height: "10px"
},
table: {
minWidth: 700
}
}));*/
const options = [
{ value: 1, label: 1 },
{ value: 2, label: 2 },
{ value: 3, label: 3 }
];
function Pruebas() {
const baseUrlAd = 'https://www.inventarios.gemcont.com/apiGemcont/compras/ingresos/index2.php';
const [data, setData]=useState([]);
const [frameworkSeleccionado, setFrameworkSeleccionado]=useState({
id_ingreso:'',
nombre:'',
dato1:'',
dato2:''
});
const handleChange=e=>{
const {name, value}=e.target;
setFrameworkSeleccionado((prevState)=>({
...prevState,
[name]: value
}))
console.log(frameworkSeleccionado);
}
/*const peticionPost = async() =>{
var f = new FormData();
f.append("nombre", frameworkSeleccionado.nombre);
f.append("dato1", frameworkSeleccionado.dato1);
f.append("dato2", frameworkSeleccionado.dato2);
f.append("METHOD", "POST_prueba");
await axios.post(baseUrlAd,f)
.then(response=>{
setData(data.concat(response.data));
}).catch(error=>{
console.log(error);
})
}*/
const peticionPost = async () => {
var f = new FormData();
f.append("nombre", frameworkSeleccionado.nombre);
/* Los datos están en la matriz bidimensional "roomInputs" */
/* f.append("dato1", roomInputs[0].dato1);
f.append("dato2", roomInputs[0].dato2);*/
f.append("data", JSON.stringify(roomInputs));
f.append("METHOD", "POST_prueba");
await axios
.post(baseUrlAd, f)
.then((response) => {
setData(data.concat(response.data));
})
.catch((error) => {
console.log(error);
});
};
//const classes = useStyles();
const [roomInputs, setRoomInputs] = useState([
{ dato1: "", dato2: "" }
]);
/*const handleRoomChange = (option, index, name) => {
const value = option.value;
console.log(value);
const list = [...roomInputs];
list[index][name] = value;
setRoomInputs(list);
};*/
/*const handleRoomChange = (value, index, name) => {
const list = [...roomInputs ];
list[index][name] = value;
setRoomInputs(list);
};*/
/*const handleRoomChange = (value, index, name) => {
setFrameworkSeleccionado((prevState) => ({
...prevState,
[name]: value
}));
};*/
const handleRoomChange = (value, index, name) => {
const list = [...roomInputs ];
list[index][name] = value;
setRoomInputs(list);
};
const handleRemoveClickRoom = (index) => {
const list = [...roomInputs];
list.splice(index, 1);
setRoomInputs(list);
};
const handleAddClickRoom = () => {
setRoomInputs([...roomInputs, { dato1: "", dato2: "" }]);
};
return (
<div className="content-wrapper">
<div className="content-header">
<div className="container-fluid">
<div className="col-sm-12">
<div class="card">
<div class="card-header">
<h3 class="card-title">Datos</h3>
</div>
<div class="card-body">
<div class="row">
<div class="col-sm-4">
<div class="input-group">
<input type="text" name="nombre"
placeholder='nombre' className="form-control" onChange={handleChange}/>
</div>
</div>
</div>
<div class="row">
<div class="col-sm-12">
<br />
<Grid item sm={12}>
<TableContainer component={Paper} variant="outlined">
<Table aria-label="customized table">
<TableHead>
<TableRow>
<TableCell>#</TableCell>
<TableCell align="left">dato1</TableCell>
<TableCell align="left">dato2</TableCell>
</TableRow>
</TableHead>
<TableBody>
{roomInputs.map((x, i) => (
<StyledTableRow key={i}>
<TableCell component="th" scope="row">
{i + 1}
</TableCell>
<TableCell align="left">
<input
type="text"
className="form-control"
name="dato1"
value={options.value}
//onChange={option => handleRoomChange(option, i, "dato1")}
onChange={event => handleRoomChange(event.target.value, i, "dato1")}
/>
</TableCell>
<TableCell align="left">
<input
type="number"
name="dato2"
className="form-control"
value={options.value}
//onChange={option => handleRoomChange(option, i, "dato2")}
onChange={event => handleRoomChange(event.target.value, i, "dato2")}
/>
</TableCell>
<TableCell align="left">
{roomInputs.length !== 1 && (
<DeleteIcon
onClick={() => handleRemoveClickRoom(i)}
style={{
marginRight: "10px",
marginTop: "4px",
cursor: "pointer"
}}
/>
)}
{roomInputs.length - 1 === i && (
<AddCircleOutlineIcon
onClick={handleAddClickRoom}
style={{ marginTop: "4px", cursor: "pointer" }}
/>
)}
</TableCell>
</StyledTableRow>
))}
</TableBody>
</Table>
</TableContainer>
</Grid>
</div>
</div>
<br />
<button className="btn btn-primary" onClick={()=>peticionPost()}> Registrar</button>
</div>
</div>
</div>
</div>
</div>
</div>
)
}
export default Pruebas
php - failed attempts
<?php
include '../../bd/global.php';
header('Access-Control-Allow-Origin: *');
//tried 1
if($_POST['METHOD']=='POST_prueba'){
unset($_POST['METHOD']);
$nombre=$_POST['nombre'];
$dato1=$_POST['dato1'];
$dato2=$_POST['dato2'];
$query="insert into ingresos2(nombre,dato1,dato2) values ('$nombre','$dato1','$dato2')";
$queryAutoIncrement="select MAX(id_ingreso) as id_ingreso from ingresos2";
$resultado=metodoPost($query, $queryAutoIncrement);
echo json_encode($resultado);
header("HTTP/1.1 200 OK");
exit();
}
//tried 2
if($_POST['METHOD']=='POST_prueba'){
unset($_POST['METHOD']);
$nombre=$_POST['nombre'];
$data=json_decode($_POST['data']);
foreach ($data as $row) {
$dato1=$row['dato1'];
$dato2=$row['dato2'];
//aqui debes hacer cada inserción en base de datos
}
$query="insert into ingresos2(nombre,dato1,dato2) values ('$nombre','$dato1','$dato2')";
$queryAutoIncrement="select MAX(id_ingreso) as id_ingreso from ingresos2";
$resultado=metodoPost($query, $queryAutoIncrement);
echo json_encode($resultado);
header("HTTP/1.1 200 OK");
exit();
}
//tried 3
if($_POST['METHOD']=='POST_prueba'){
unset($_POST['METHOD']);
$nombre=$_POST['nombre'];
$query="insert into ingresos(nombre) values ('$nombre')";
$queryAutoIncrement="select MAX(id_ingreso) as id_ingreso from ingresos";
$resultado=metodoPost($query, $queryAutoIncrement);
echo json_encode($resultado);
$num_elementos=0;
$sw=true;
while ($num_elementos < count($id_detalle))
{
$sql_detalle = "INSERT INTO detalle_ingresos(id_ingreso, dato1, dato2) VALUES ('$idingresonew', '$idarticulo[$num_elementos]','$dato1[$num_elementos]','$dato2[$num_elementos]')";
ejecutarConsulta($sql_detalle) or $sw = false;
$num_elementos=$num_elementos + 1;
}
return $sw;
header("HTTP/1.1 200 OK");
exit();
}
header("HTTP/1.1 400 Bad Request");
?>
mysql
try to do 'json_encode' before putting the array into the base
example :
$array = [1,2,3,4,5];
$array = json_encode($array);
if the data does not fit into the database, change the field from 'varchar' to 'json' , then everything will work
your php sript won't work, it has a lot of errors
This line of your code:
$query="insert into ingresos2(nombre,dato1,dato2) values ​​('$nombre','$dato1','$dato2')";
should look like this:
$query="INSERT iNTO ingresos2 (nombre,dato1,dato2) values ​​($nombre,$dato1,$dato2)";
and in all other inserts the same way (if it's easy to explain)
ideally you should bind your parameters before Insert here is an example :
$this->db->openPdo();
$update = "INSERT INTO imported_error_logs (product_id,errors)
VALUES(:productId,:error)";
$sql = $this->db->pdo->prepare($update);
$sql->execute([
':error' => $error,
':productId' => $productId,
]);

Error: DataTables warning: table id=DataTables_table_0 - Ajax error. In Laravel

I was using from a Laravel project well, But today, this error appears on one of the pages:
Error: DataTables warning: table id=DataTables_table_0 - Ajax error.
For more information about this error, please see
http://datatables.net/tn/7
The recourses codes:
#extends('admin.layouts.app')
#section('title', getOption('app_name') . ' - Orders')
#section('content')
#php
$status = $status ?? false;
$dataURL = $status ? "/admin/orders-filter-ajax/$status/data" : "/admin/orders-ajax/data";
#endphp
<div class="row">
<div class="col-md-12" style="margin-bottom: 5px;">
<div class="btn-group">
<button type="button" class="btn btn-info btn-sm hide" id="apply-all">Apply</button>
</div>
<div class="btn-group">
ALL
Pending
In Progress
Completed
Partial
Refunded
Cancelled
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="panel panel-default">
<div class="panel-body">
<form id="frm-apply-all" action="{{ url('/admin/orders-bulk-update') }}" method="post">
{{ csrf_field() }}
</form>
<div class="table-responsive">
<table class="table table-bordered mydatatable table-hover" style="width: 99.9%">
<thead>
<tr>
<th><input type="checkbox" class="input-sm checkbox-all"></th>
<th>#lang('general.order_id')</th>
<th>Api #lang('general.order_id')</th>
<th>#lang('general.user')</th>
<th>#lang('general.service')</th>
<th>#lang('general.package')</th>
<th>#lang('general.link')</th>
<th>#lang('general.amount')</th>
<th>#lang('general.quantity')</th>
<th>#lang('general.start_counter')</th>
<th>#lang('general.remains')</th>
<th>#lang('general.status')</th>
<th>#lang('general.date')</th>
<th class="text-center" width="5%">#lang('general.action')</th>
</tr>
</thead>
</table>
</div>
</div>
</div>
</div>
</div>
#endsection
#push('scripts')
<script>
$(function () {
$('.mydatatable').DataTable({
processing: true,
serverSide: true,
pageLength: 25,
order: [[1, 'desc']],
ajax:'{!! url($dataURL) !!}',
columns: [
{data: 'bulk', name: 'bulk', orderable: false, searchable: false},
{data: 'id', name: 'id'},
{data: 'api_order_id', name: 'api_order_id'},
{data: 'user.name', name: 'user.name'},
{data: 'package.service.name', name: 'package.service.name'},
{data: 'package.name', name: 'package.name'},
{data: 'link', name: 'link'},
{data: 'price', name: 'price', sortable: false, searchable: false},
{data: 'quantity', name: 'quantity', sortable: false, searchable: false},
{data: 'start_counter', name: 'start_counter', sortable: false, searchable: false},
{data: 'remains', name: 'remains', sortable: false, searchable: false},
{data: 'status', name: 'status'},
{data: 'created_at', name: 'created_at'},
{data: 'action', name: 'action', orderable: false, searchable: false},
]
});
$(document).on('click', '.checkbox-all', function () {
$('.row-checkbox').trigger('click');
$('#apply-all').removeClass('hide');
});
$(document).on('click', '.row-checkbox', function () {
$('#apply-all').removeClass('hide');
var t = $(this);
if (t.is(':checked')) {
t.parents('tr').find('.row-edit').removeAttr('readonly');
t.parents('tr').attr('style', 'background-color:#dedede');
} else {
t.parents('tr').find('.row-edit').attr('readonly', 'readonly');
t.parents('tr').removeAttr('style');
}
});
$('#apply-all').on('click', function (e) {
var form = $('#frm-apply-all');
var isAnyRowSelected = false; // check if it shouldn't submit empty form
bootbox.confirm({
message: "Confirm to apply bulk update?",
buttons: {
cancel: {
label: 'Cancel',
className: 'btn-default'
},
confirm: {
label: 'Confirm',
className: 'btn-primary'
},
},
callback: function (result) {
if (result) {
// Iterate over all checkboxes in the table
$('.row-checkbox').each(function () {
var t = $(this);
if (t.is(':checked')) {
isAnyRowSelected = true; // Row selected
// Order id
$(form).append(
$('<input>')
.attr('type', 'hidden')
.attr('name', t.attr('name'))
.val(t.val())
);
// start count
$(form).append(
$('<input>')
.attr('type', 'hidden')
.attr('name', 'start_counter[' + t.val() + ']')
.val($('input[name="start_counter[' + t.val() + ']"]').val())
);
// remains
$(form).append(
$('<input>')
.attr('type', 'hidden')
.attr('name', 'remains[' + t.val() + ']')
.val($('input[name="remains[' + t.val() + ']"]').val())
);
// status
$(form).append(
$('<input>')
.attr('type', 'hidden')
.attr('name', 'status[' + t.val() + ']')
.val($('select[name="status[' + t.val() + ']"]').find(':selected').text())
);
}
});
if (isAnyRowSelected) {
form.submit();
}
}
}
});
});
});
</script>
#endpush
I didn't change any thing in my project today
It worked yesterday well:(

Datatable remove row on mobile

I use laravel with datatable to display large data table.
I have a delete button at the end of each row to delete record from my database.
I use ajax and if it's a success I remove the row.
It work well on desktop but it doesn't work on mobile (except if I set computer version).
Here my table :
<table class="datatable table table-striped- table-bordered table-hover table-checkable" id="m_table_1">
<thead>
<tr>
<th>Numéro</th>
<th>Bâtiment</th>
<th>Nature</th>
<th>Options</th>
</tr>
</thead>
</table>
My js to load data :
var table = $('.datatable').DataTable({
responsive: true,
ajax: '{{ route('lots.clientSide') }}',
deferRender: true,
scrollY: '500px',
scrollCollapse: true,
scroller: true,
stateSave: true,
select: true,
language: {
url: "//cdn.datatables.net/plug-ins/1.10.16/i18n/French.json",
select: {
rows: "%d éléments sélectionnés"
}
},
columns: [
{ data: 'id' },
{ data: 'batiment.nom', defaultContent: "----" },
{ data: 'nature' },
{ data: null }
],
columnDefs:[
{targets:-1,title:"Options",width: "10%",orderable:!1,render:function(a,t,e,n){
var slug = e.id;
var url = 'show';
var url_delete = "lots/delete/"+e.id;
return '\n<a href="'+url+'" class="m-portlet__nav-link btn m-btn m-btn--hover-brand m-btn--icon m-btn--icon-only m-btn--pill" title="View">\n'+
'<i class="la la-eye"></i>\n'+
'</a>'+
'<span class="dropdown">\n'+
'<a href="#" class="btn m-btn m-btn--hover-brand m-btn--icon m-btn--icon-only m-btn--pill" data-toggle="dropdown" aria-expanded="true">\n'+
'<i class="la la-ellipsis-h"></i>\n'+
'</a>\n'+
'<div class="dropdown-menu dropdown-menu-left">\n'+
'<a class="dropdown-item" href="#"><i class="la la-edit"></i> Editer</a>\n'+
'<button class="delete dropdown-item" data-href="'+url_delete+'"><i class="la la-trash"></i> Supprimer</button>\n'+
'</div>\n'+
'</span>\n'
}}
]
});
And my code for the remove :
$(document).on('click', '.delete', function(e){
var $this = $(this);
table.row($this.parents('tr')).remove().draw(false);
alert("click");
$.ajax({
type: 'GET',
url: $this.data('href'),
dataType: 'json',
success: function( data ) {
},
error: function(xhr, status, error) {
alert("fail");
}
})
});
I tried with debug tools on computer and I've got nothing on console.
If I use the function on computer, it work. But if I reduce size of the windows, it doesn't work under a certain size.
Is it normal ? Can I do something about it ?
Thank
I manage to avoid this problem by not hidding delete button on mobile.

Unexpected token :, Ajax success message Laravel

I'm trying to Ajax success message in Ajax success method, but i got Unexpected token ( error on my console by using inspect element browser.
here's my Ajax code so far :
$(document).ready(function() {
var rawDORecordsDataTable = $('#raw_do_record_table').DataTable(
{
dom: 'Blrtip',
orderCellsTop: true,
responsive: true,
processing: true,
serverSide: true,
iDisplayLength: 50,
ajax: {
url: '{{ route('raw_do_record.list') }}',
data: function(data) {
data._token = '{{ csrf_token() }}';
data.do_date = $('#search_date').val();
data.do_status = 0;
},
type: 'POST',
},
columns: [
{ data: 'do_no', name: 'do_no' },
{ data: 'do_status', name: 'do_status' },
{ data: 'customer', name: 'customer' },
{ data: 'store_isn', name: 'store_isn' },
{ data: 'warehouse_status', name: 'warehouse_status' },
{ data: 'do_date', name: 'do_date' },
{ data: 'delivery_status', name: 'delivery_status' },
{ data: 'action', name: 'action', orderable: false, searchable: false },
] ,
searchCols: [
null ,
{ "search" : 0} ,
],
buttons: [
#if(Gate::allows('views',[[Department::LOGISTICS]]))
{ text: 'Generate All',
action: function ( e, dt, node, config ) {
$('#generate_all_modal').modal('show')
}
},
#endif
{ text: '<i class="fa fa-refresh"></i> Refresh DO',
action: function ( e, dt, node, config ) {
$('#refresh_do_modal').modal('show')
}
}
],
})
.on('click', 'a.stop', function(e) {
$.ajax({
url: '{{ route('raw_do_record.list') }}',
type: 'POST',
data: {
'_token' : '{{csrf_token() }}',
},
success: function(data) {
alert("asd");
},
error: function(data) {
alert("asdasd");
}
});
});
and here's the modal html :
<div class="modal fade bs-modal-sm" id="stop_modal" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-dialog modal-sm">
<div class="modal-content">
{{ Form::open([
'method' => 'POST',
'id' => 'stop-form'
]) }}
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true"></button>
<h4 class="modal-title">Stop Confirmation</h4>
</div>
<div class="modal-body">
<div class="form-group">
<label>Are you sure want to stop the process?<br>This DO no longer useable</label>
</div>
</div>
<div class="modal-footer">
<button class="btn sbold btn-danger" type="submit">
</i> Yes
</button>
<button type="button" class="btn sbold blue" data-dismiss="modal">No</button>
</div>
{{ Form::close() }}
</div>
</div>
any idea ?

Datatable jquery + ajax + php can't get data in table (Server-side processing)

I'm using datatable following this example https://datatables.net/examples/data_sources/server_side.html
So my table is:
<table cellpadding="0" cellspacing="0" border="0" class="display" id="tabellaGlossario">
<thead>
<th>
<td>Voce</td>
<td>Sinonimi</td>
<td>Sigla</td>
<td>Macrosettore</td>
<td>Microsettore</td>
<td>Sinonimi</td>
<td>Sigla</td>
<td>Macrosettore</td>
<td>Microsettore</td>
</th>
</thead>
<tfoot>
<th>
<td>Voce</td>
<td>Sinonimi</td>
<td>Sigla</td>
<td>Macrosettore</td>
<td>Microsettore</td>
<td>Sinonimi</td>
<td>Sigla</td>
<td>Macrosettore</td>
<td>Microsettore</td>
</th>
</tfoot>
</table>
My js:
oTable = $('#tabellaGlossario').dataTable({
"bJQueryUI": true,
"sPaginationType": "full_numbers",
"sDom": '<""f>t<"F"lp>',
"processing": true,
"serverSide": true,
"ajax": "Modules/Glossario/View/Glossario.Table.View.php?lingua_select=2",
});
My ajax returned:
{
"draw": 1,
"recordsTotal": 1,
"recordsFiltered": 1,
"data": [
[
"1",
"2",
"1",
"1",
"1",
"Parola italiana",
"Sinonimo italiano",
"Sigla ita",
"Note ita"
]
]
}
My problem is that i always get "No data available in table" as table results. But as you can see ajax has some results (1 in this example).
It seems my code is the same as the one in official example.
Can't understand why data are not showed in table (and i get no error in browser console).
Are you using some dynamic loading or any kind of routing?
For example angularjs ngroute or some framework's.
In that case it can't work (not as you're doing). You can follow some guide like this or example like this http://jsfiddle.net/qu4a7j24/3/
<div ng-app='testTableApp'>
<div class="container">
<div ng-controller="mainTable">
<form action="" method="POST" class="form-horizontal" role="form">
<div class="form-group">
<legend>Filters</legend>
</div>
<div class="form-group">
<div class="col-sm-10 col-sm-offset-2">
<input type="text" value="0" ng-change='reloadData()' ng-model="start">
<input type="text" value="50" ng-change='reloadData()' ng-model="end">
</div>
</div>
</form>
<table datatable="" dt-options="dtOptions" dt-columns="dtColumns" class="table table-striped table-bordered"></table>
</div>
</div>
</div>
var testTableApp = angular.module( 'testTableApp', ['ngRoute', 'ngResource', 'datatables', 'datatables.tabletools', 'datatables.bootstrap', 'datatables.fixedheader'] );
console.log( testTableApp );
testTableApp.controller("mainTable",
[ '$scope', 'DTOptionsBuilder', 'DTColumnBuilder',
function ( $scope, DTOptionsBuilder, DTColumnBuilder){
$scope.dataSource = "http://dt.ishraf.com/ajax.php";
$scope.start = 0;
$scope.end = 5000;
$scope.getDataSource = function(obj,prefix){
var src = $scope.dataSource;
var str = [];
for(var p in obj) {
if (obj.hasOwnProperty(p)) {
var k = prefix ? prefix + "[" + p + "]" : p, v = obj[p];
str.push(typeof v == "object" ?
serialize(v, k) :
encodeURIComponent(k) + "=" + encodeURIComponent(v));
}
}
return src + "?" + str.join("&");
}
var dsParams = {
start : $scope.start,
end : $scope.end
}
$scope.dsString = $scope.getDataSource( dsParams );
$scope.buildTable = function(){
return DTOptionsBuilder
.newOptions()
.withOption('ajax', {
// Either you specify the AjaxDataProp here
dataSrc: 'data',
url: $scope.dsString,
type: 'POST'
}).
withOption( 'lengthMenu', [
[10, 20, 50, 100, 150, 300, 500],
[10, 20, 50, 100, 150, 300, 500]
])
.withTableTools('bower_components/datatables-tabletools/swf/copy_csv_xls_pdf.swf')
.withTableToolsButtons([
{
"sExtends": "copy",
"sButtonText": "<i class='fa fa-copy'></i> | Copy",
"fnInit": function (nButton, oConfig) {
$(nButton).addClass('btn btn-success');
}
},
{
"sExtends": "print",
"sButtonText": "<i class='fa fa-print'></i> | Print",
"fnInit": function (nButton, oConfig) {
$(nButton).addClass('btn btn-danger');
}
},
{
"sExtends": "csv",
"sButtonText": "<i class='fa fa-file-o'></i> | CSV",
"fnInit": function (nButton, oConfig) {
$(nButton).addClass('btn btn-primary');
}
},
{
"sExtends": "pdf",
"sButtonText": "<i class='fa fa-file-pdf-o'></i> | PDF",
"fnInit": function (nButton, oConfig) {
$(nButton).addClass('btn btn-warning');
}
}
])
.withFixedHeader({
bottom: true
})
.withDOM('<"clear"><"#top.hidden-print"<".row"<".col-md-6"i><".col-md-6"f>><".row"<".col-md-6"l><".col-md-6"p>><"clear">T>rt')
;
}
$scope.dtOptions = $scope.buildTable();
$scope.buildColumns = function(){
return [
DTColumnBuilder.newColumn('id').withTitle('ID'),
DTColumnBuilder.newColumn('firstName').withTitle('First name'),
DTColumnBuilder.newColumn('lastName').withTitle('Last name'),
DTColumnBuilder.newColumn('city').withTitle('city'),
DTColumnBuilder.newColumn('state').withTitle('state'),
DTColumnBuilder.newColumn('zip').withTitle('zip'),
DTColumnBuilder.newColumn('country').withTitle('country'),
DTColumnBuilder.newColumn('phone').withTitle('phone'),
DTColumnBuilder.newColumn('email').withTitle('email')
];
}
$scope.dtColumns = $scope.buildColumns();
$scope.reloadData = reloadData;
$scope.dtInstance = {};
function reloadData() {
var resetPaging = false;
$scope.dtInstance.reloadData(callback, resetPaging);
}
function callback(json) {
console.log(json);
}
}
]);
or just dynamic create the table (.load jquery can be useful)

Categories