jquery datatable not pagiging except first page - datatable

I have a datatable with server-sider processising.
Data come from table expected but it doesnt page by datatable. I see in debug total record count 14 of the database aaData whic gonna display is 5,
so I expect there will be 3 page.. but only 1 page diplayed and 5 rows in the page.
here is my tabl html:
<table style="text-align: center" class="table table-striped table-bordered table-hover" id="usersTable">
<thead>
<tr>
<th>
User Name
</th>
<th>
Account
</th>
<th>
Enable
</th>
<th>
Remark
</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
and datatable def:
var tableObject = $("#usersTable").dataTable({
"bProcessing": true,
"bServerSide": true,
"sAjaxSource": "../../Controller/UserManagementControllercopy.php5",
"aoColumns": [
{ "mDataProp": "0", "sWidth": "40%", "bSearchable": false },
{ "mDataProp": "1", "sWidth": "20%"},
{ "mDataProp": "3", "sWidth": "20%" },
{ "mDataProp": "2", "sWidth":"20%" }
],
"fnServerData": function (sSource, aoData, fnCallback){
$.ajax({
"dataType": "json",
"contentType": "application/json; charset=utf-8",
"type": "GET",
"url": sSource,
"data": aoData,
"success": function(result){
fnCallback(result);
},
error: function (xhr, textStatus, error){
debugger
if (typeof console == "object") {
console.log(xhr.status + "," + xhr.responseText + "," + textStatus + "," + error);
}
}});
},
"oLanguage": {
"sLengthMenu": '<select>' +
'<option value="5">5</option>' +
'<option value="10">10</option>' +
'<option value="20">20</option>' +
'<option value="30">30</option>' +
'<option value="40">40</option>' +
'<option value="50">50</option>' +
'</select> Show'
},
"fnDrawCallback": function(){
},
"aaSorting": [
[1, 'asc']
],
"aLengthMenu": [
[5, 15, 20, -1],
[5, 15, 20, "All"] ],
"iDisplayLength": 5
});
and servercode:
$aColumns = array( 'USERNAME', 'ACCOUNT', 'REMARK', 'ENABLE');
$sQuery = " SELECT USERNAME,ACCOUNT,REMARK,ENABLE FROM users LIMIT ".$_GET['iDisplayStart'].", ".$_GET['iDisplayLength'].";";
$dbObject = Connection::getConnection();
$request = $dbObject->dbh->prepare($sQuery);
if ($request->execute())
{
$resultData["Data"] = $request->fetchAll(PDO::FETCH_ASSOC);
$sQuery = "SELECT COUNT(USERNAME) FROM users";
$request = $dbObject->dbh->prepare($sQuery);
$request->execute();
$iTotal = $request->fetchColumn(0);
$output = array(
"sEcho" => intval($_GET['sEcho']),
"iTotalRecords" => intval($iTotal),
"iTotalDisplayRecords" => intval($_GET['iDisplayLength']),
"aaData" => array()
);
for ( $j=0 ; $j<count($resultData["Data"]) ; $j++ )
{
$aRow = $resultData["Data"][$j];
$row = array();
$output["Success"]=true;
echo json_encode($output);
}
and here how returned data from get request of datatable seem is:
(chrome developer console)

you are returning the wrong value for iTotalDisplayRecords in the json array. It should be the Total records, after filtering (i.e. the total number of records after filtering has been applied - not just the number of records being returned in this result set)
see the documentation and refer this
https://datatables.net/forums/discussion/512/clarification-of-itotalrecords-and-itotaldisplayrecords

Related

Ajax filter column datatable

I'd want to display result by column dropdown filter. But after choose table doesn't update result.
My main goal is filter by "Компания" column and that selector must be on top of the table.
`
$(document).ready(function() {
var exampleDataTable = $('#example').DataTable({
responsive: true,
colReorder: true,
dom: 'Bfrtip',
buttons: [
{
extend: 'excel',
exportOptions: {
columns: ':visible'
}
},
'colvis'
],
language: {
buttons: {
colvis: 'Отображение столбцов'
},
"processing": "Подождите...",
"search": "Поиск:",
"lengthMenu": " _MENU_ ",
"info": "Показано с _START_ до _END_ записей из _TOTAL_",
"infoEmpty": "Записи с 0 до 0 из 0 записей",
"infoFiltered": "(отфильтровано из _MAX_ записей)",
"infoPostFix": "",
"loadingRecords": "Загрузка записей...",
"zeroRecords": "Записи отсутствуют.",
"emptyTable": "В таблице отсутствуют данные",
"paginate": {
"first": "Первая",
"previous": "<",
"next": ">",
"last": "Последняя"
},
"aria": {
"sortAscending": ": активировать для сортировки столбца по возрастанию",
"sortDescending": ": активировать для сортировки столбца по убыванию"
}
},
"iDisplayLength": 10,
"aLengthMenu": [[ 3, 10, 20, 50, 100 ,-1],[ 3, 10,20,50,100,"все"]],
stateSave: true,
"fnCreatedRow": function(nRow, aData, iDataIndex) {
$(nRow).attr('id', aData[0]);
},
'serverSide': 'true',
'processing': 'true',
'paging': 'true',
'order': [],
'ajax': {
'url': 'fetch_data.php',
'type': 'post',
'data': {
from_attr_1_l: from_attr_1_l,
from_attr_2_l: from_attr_2_l
},
},
initComplete: function () {
this.api().columns().every(function () {
var column = this;
var select = $('<select><option value=""></option></select>')
.appendTo($(column.footer()).empty())
.on('change', function () {
var val = $.fn.dataTable.util.escapeRegex(
$(this).val()
);
column
.search(val ? '^' + val + '$' : '', true, false)
.draw();
});
column.data().unique().sort().each(function (d, j) {
select.append('<option value="' + d + '">' + d + '</option>')
});
});
} }); });
`
<div class="container-fluid">
<div class="row">
<div class="container">
<div class="row">
<div class="col-md-8">
<table id="example" class="table">
<thead>
<th>Id</th>
<th>Номер</th>
<th>ФИО</th>
<th>Дата</th>
<th>Срок</th>
<th>Кол-во мест</th>
<th>Метка</th>
<th>ИНН</th>
<th>Телефон</th>
<th>КПП</th>
<th>Компания</th>
<th>Адрес</th>
<th>Email</th>
<th>Ответственный</th>
<th>Партнер</th>
<th>К. телефон</th>
<th>К. email</th>
<th></th>
</thead>
<tbody>
</tbody>
<tfoot>
<tr>
<th>Id</th>
<th>Номер</th>
<th>ФИО</th>
<th>Дата</th>
<th>Срок</th>
<th>Кол-во мест</th>
<th>Метка</th>
<th>ИНН</th>
<th>Телефон</th>
<th>КПП</th>
<th>Компания</th>
<th>Адрес</th>
<th>Email</th>
<th>Ответственный</th>
<th>Партнер</th>
<th>К. телефон</th>
<th>К. email</th>
<th></th>
</tr>
</tfoot>
</table>
</div>
</div>
</div>
</div>
</div>
I used different solutions also from https://datatables.net/examples/api/multi_filter_select.html and https://datatables.net/forums/discussion/73081/select-dropdown-list-filter but didn't work.

Individual column filtering using datatable

My target is to have an individual filtering for column. My reference is: https://datatables.net/extensions/fixedheader/examples/options/columnFiltering.html
The problem I am encountering right now when I type, my datatable doesn't do any filtering and it shows an error regarding CURSORPOSITION:
I followed the guide thoroughly and made a lots of research but I still failed to achieve my goal. I hope you can help me
Views:
<table id="example" class="table table-bordered table-hover table-striped is-narrow is-hoverable is-fullwidth text-nowrap" style="width: 100%;">
<thead>
<tr>
<th>TESTING ID</th>
<th>TESTING ACTION</th>
<th>TESTING DESC</th>
<th>TESTING Date</th>
<th>TESTING VENUE</th>
<th>TESTING TICKET</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
Ajax:
$(document).ready(function() {
$('#example thead tr')
.clone(true)
.addClass('filters')
.appendTo('#example thead');
table = $('#example').DataTable({
dom: 'lfrtip',
"processing": false, //Feature control the processing indicator.
"serverSide": true, //Feature control DataTables' server-side processing mode.
orderCellsTop: true,
fixedHeader: true,
initComplete: function () {
var api = this.api();
// For each column
api
.columns()
.eq(0)
.each(function (colIdx) {
// Set the header cell to contain the input element
var cell = $('.filters th').eq(
$(api.column(colIdx).header()).index()
);
var title = $(cell).text();
$(cell).html('<input type="text" placeholder="' + title + '" />');
// On every keypress in this input
$(
'input',
$('.filters th').eq($(api.column(colIdx).header()).index())
)
.off('keyup change')
.on('change', function (e) {
// Get the search value
$(this).attr('title', $(this).val());
var regexr = '({search})'; //$(this).parents('th').find('select').val();
var cursorPosition = this.selectionStart;
// Search the column for that value
api
.column(colIdx)
.search(
this.value != ''
? regexr.replace('{search}', '(((' + this.value + ')))')
: '',
this.value != '',
this.value == ''
)
.draw();
})
.on('keyup', function (e) {
e.stopPropagation();
$(this).trigger('change');
$(this)
.focus()[0]
.setSelectionRange(cursorPosition, cursorPosition);
});
});
},
// Load data for the table's content from an Ajax source
"ajax": {
"url": "<?php echo site_url('controller/lists')?>",
"type": "POST",
async:true,
dataType: "json",
"data": function(data){
},
},
//Set column definition initialization properties.
"columnDefs": [
{
"targets": [ 0 ], //first column
"orderable": false, //set not orderable
},
{
"targets": [ -1 ], //last column
"orderable": false, //set not orderable
},
],
});
});

How to show the detail in a Master-Detail form with Datatables Jquery

I am designing a system with Net Core 5 MVC, I have to show a Master-Detail, I already have the Master view that contains a Datatable, I would like that when clicking on the ID field (according to the image), the view with the detail would be displayed , but I don't know how to call the Detail view.
Header image
The code I have in the master is the following (Controller, JS, View):
This's the controller code:
[HttpPost]
public IActionResult LoadDataGrid()
{
var draw = Request.Form["draw"].FirstOrDefault();
var start = Request.Form["start"].FirstOrDefault();
var length = Request.Form["length"].FirstOrDefault();
var sortColumn = Request.Form["columns[" + Request.Form["order[0][column]"].FirstOrDefault() + "][name]"].FirstOrDefault();
var sortColumnDir = Request.Form["order[0][dir]"].FirstOrDefault();
var searchValue = Request.Form["search[value]"].FirstOrDefault().ToUpper();
pageSize = length != null ? Convert.ToInt32(length) : 0;
skip = start != null ? Convert.ToInt32(start) : 0;
recordsTotal = 0;
List<VDiagramaMasterModel> ListVDiagramaMasterModel = Singleton.Instance.EntityManager.GetEntities<VDiagramaMasterModel>();
ListVDiagramaMasterModel = (from d in ListVDiagramaMasterModel select d).ToList();
/* Si tenemos una cadena de busqueda */
if (searchValue != "")
{
ListVDiagramaMasterModel = ListVDiagramaMasterModel.Where(x => x.DiagramaId.ToString().Contains(searchValue) ||
x.FechaElaboracion.ToString().Contains(searchValue) ||
x.DiagramaNumber.ToUpper().ToString().Contains(searchValue) ||
x.DiagramaName.ToUpper().ToString().Contains(searchValue) ||
x.StatusProcesoName.ToUpper().ToString().Contains(searchValue)).ToList();
}
recordsTotal = ListVDiagramaMasterModel.Count;
/* Reordenar segun lo solicitado en el Grid */
switch (sortColumn)
{
case "diagramaId":
if (sortColumnDir == "asc")
ListVDiagramaMasterModel = ListVDiagramaMasterModel.OrderBy(x => x.DiagramaId).Skip(skip).Take(pageSize).ToList();
else
ListVDiagramaMasterModel = ListVDiagramaMasterModel.OrderByDescending(x => x.DiagramaId).Skip(skip).Take(pageSize).ToList();
break;
default:
break;
}
return Json(new { draw, recordsFiltered = recordsTotal, recordsTotal, data = ListVDiagramaMasterModel });
}
The Javascript File where I load the Master Datatable
$(document).ready(function () {
filter: true, // Filtrado de datos
info: true, // Resultado de busquedas
processing: true, // Muestra/Oculta la leyenda procesando
scrollX: true, // Scroll Horizontal
select: true, // Permite seleccionar el renglon
ordering: true, // Activa el ordenamiento
autoWidth: false, // Apaga el ancho automatico
scroller: { "loadingIndicator": true }, // Complemento de representación virtual para DataTables para mostrar muchos datos en la pantalla muy rápidamente.
serverSide: true, // Habilitar procesamiento del lado del servidor
deferRender: true, // Habilitar renderizado diferido para cargar con AJAX
responsivePriority: 1,
data: null,
ajax: {
url: "/DiagramaMaster/LoadDataGrid/",
type: "POST",
datatype: "json",
},
columns: [ // Definicion de columnas, ID's
{
data: "diagramaId", name: "diagramaId",
render: function (data) {
/* return "<a href='/DiagramaMaster/Details/" + data + "'>" + ("00000" + data).slice(-5) + "</a>"; */
return "<a href='/DiagramaDetail/Details/" + data + "'>" + ("00000" + data).slice(-5) + "</a>";
/*return "<a href ='#WinModal' data-id='" + data + "' data-bs-toggle='modal' class='btnGrdDetails'>" + ("0000" + data).slice(-4) + "</a>";*/
}
},
{
data: "tipoProcesoId", name: "tipoProcesoId",
render: function (data) {
return ("00" + data).slice(-2);
}
},
{ data: "tipoProcesoName", name: "tipoProcesoName"},
{
data: "fechaElaboracion", name: "fechaElaboracion",
render: function (value) {
var dt = new Date(value).toLocaleDateString('es-MX', { year: 'numeric', month: '2-digit', day: '2-digit' });
return dt; }
},
{ data: "diagramaNumber", name: "diagramaNumber"},
{ data: "diagramaName", name: "diagramaName"},
{ data: "diagramaDescripcion", name: "diagramaDescripcion"},
{ data: "diagramaNotas", name: "diagramaNotas" },
{
data: "totalTelaKilos", name: "totalTelaKilos",
render: $.fn.dataTable.render.number(',', '.', 3, '')
},
{
data: "incluirCuellos", name: "incluirCuellos",
render: function (data, type, row) {
if (data == true) { return '<input type="checkbox" checked disabled>'; }
else { return '<input type="checkbox" readonly>'; }
return data;
}
},
{
data: "incluirEstampe", name: "incluirEstampe",
render: function (data, type, row) {
if (data == true) { return '<input type="checkbox" checked disabled readonly>'; }
else { return '<input type="checkbox" readonly>'; }
return data;
}
},
{ data: "statusProcesoId", name: "statusProcesoId" },
{ data: "statusProcesoName", name: "statusProcesoName" },
{ data: "referenciaId", name: "referenciaId"},
{
data: "actionBar", name: "actionBar", title: "Acción", width: "100px", sortable: false,
render: function (data, type, full, meta) {
return "<button href='#WinModal' id='btnDetails' data-id='" + full.diagramaId + "' data-bs-toggle='modal' type='button' class='btnDetails btn btn-primary btn-sm' title='Ver'><i class='fa-solid fa-file-lines'></i></button> " +
"<button href='#WinModal' id='btnEdit' data-id='" + full.diagramaId + "' data-bs-toggle='modal' type='button' class='btnEdit btn btn-primary btn-sm' title='Editar'><i class='fa-solid fa-pencil'></i></button> " +
"<button href='#WinModal' id='btnDelete' data-id='" + full.diagramaId + "' data-bs-toggle='modal' type='button' class='btnDelete btn btn-danger btn-sm' title='Eliminar'><i class='fa-solid fa-trash'></i></button> ";
}
},
],
order: [[0, 'asc']],
// 0:diagramaId, 1:tipoProcesoId, 2:tipoProcesoName, 3:fechaElaboracion, 4:diagramaNumber, 5:diagramaName
// 6:diagramaDescripcion, 7:diagramaNotas, 8:totalTelaKilos, 9:incluirCuellos, 10:incluirEstampe,
// 11: statusProcesoId, 12:statusProcesoName, 13:referenciaId, 14:actionBar
columnDefs: [
{ visible: false, targets: [1, 6, 7, 11] },
{ searchable: false, targets: [1, 2, 6, 7, 8, 9, 10, 11, 12, 13, 14] },
{ sortable: false, targets: [1, 6, 7, 8, 9, 10, 11, 13, 14] },
{ className: "dt-body-center", targets: [0, 9, 10, 12, 13, 14] },
{ className: "dt-body-right", targets: [8] },
{ "width": "20px", "targets": [0] },
{ "width": "25px", "targets": [3, 9, 10] },
{ "width": "30px", "targets": [2, 13] },
{ "width": "70px", "targets": [8, 12] },
{ "width": "80px", "targets": [4] },
{ "width": "350px", "targets": [5] },
],
// Cargar el Idioma Español //
language: {
url: "/js/language_pack/es-ES.json"
},
});
/* ******************** */
/* Dibujar la DataTable */
/* ******************** */
tableBase.draw()
}); // Fin $(document).ready(function () {});
View to load the master
#* Archivo cshtml para cargar el Maestro #*
<div id="divContainer" class="container-fluid">
<h1>Listado de Diagramas</h1>
<hr/>
<div class="row">
<p><button href="#WinModal" id="btnNew" type="button" asp-action="Create" class="btnNew btn btn-primary btn-md" data-bs-toggle="modal" title="Nuevo Diagrama" ><i class="fa-solid fa-plus"></i> Nuevo</button></p>
</div>
<span class="text-danger">#ViewBag.ErrorMessage</span>
<div class="table table-responsive">
<table id="tableGrid" class="display cell-border"">
<thead style="font-size:12px; color: white; background-color: #2C3E50;">
<tr>
<th>#Html.DisplayNameFor(model => model.DiagramaId)</th>
<th>#Html.DisplayNameFor(model => model.TipoProcesoId)</th>
<th>#Html.DisplayNameFor(model => model.TipoProcesoName)</th>
<th>#Html.DisplayNameFor(model => model.FechaElaboracion)</th>
<th>#Html.DisplayNameFor(model => model.DiagramaNumber)</th>
<th>#Html.DisplayNameFor(model => model.DiagramaName)</th>
<th>#Html.DisplayNameFor(model => model.DiagramaDescripcion)</th>
<th>#Html.DisplayNameFor(model => model.DiagramaNotas)</th>
<th>#Html.DisplayNameFor(model => model.TotalTelaKilos)</th>
<th>#Html.DisplayNameFor(model => model.IncluirCuellos)</th>
<th>#Html.DisplayNameFor(model => model.IncluirEstampe)</th>
<th>#Html.DisplayNameFor(model => model.StatusProcesoId)</th>
<th>#Html.DisplayNameFor(model => model.StatusProcesoName)</th>
<th>#Html.DisplayNameFor(model => model.ReferenciaId)</th>
<th></th>
</tr>
</thead>
<tbody style="font-size:12px;">
</tbody>
</table>
</div>
</div>
#section scripts{
<!-- Para usar las funciones del grid -->
<script src="/js/dtg_config/diagramamaster.js"></script>
}
In order not to extend too much, the Detail is set up in a similar way (View, Controller, JS), but as I mentioned, I don't know how to do it so that when the ID is clicked, it brings me the view with the Detail and puts it in a DataTable, the following code is where I put together the DT of the detail.
// js para configurar la DataTable del detalle
$(document).ready(function () {
/* Nombre del Modelo con el que se trabajara, se */
/* pasa como parametro a la accion del controlador */
//var workingModel = { Name: "CatConsignatarioModel" };
/* *********************************************** */
$('#tableGrid').DataTable({
dom: "lfrtip", // DOM [B]: Butons (PDF, Excel, etc.), [l]:Cantidad [f]:Filtro, [r]:Visualizacion del proceso, [t]:Tabla [i]:Informacion, [p]:Paginación
//buttons: ["copy", "excel"], // Botones de "copy", "excel", "pdf", "csv" y "print"
filter: true, // Filtrado de datos
info: true, // Resultado de busquedas
processing: true, // Muestra/Oculta la leyenda procesando
scrollX: true, // Scroll Horizontal
select: true, // Permite seleccionar el renglon
ordering: true, // Activa el ordenamiento
autoWidth: false, // Apaga el ancho automatico
responsive: true, // Tabla responsiva
lengthMenu: [[50, 100, 150, -1], [50, 100, 150, "All"]],
responsivePriority: 1,
scroller: { "loadingIndicator": true }, // Complemento de representación virtual para DataTables para mostrar muchos datos en la pantalla muy rápidamente.
serverSide: true, // Habilitar procesamiento del lado del servidor
deferRender: true, // Habilitar renderizado diferido para cargar con AJAX
responsivePriority: 1,
data: null,
ajax: {
url: "/DiagramaDetail/LoadDataGrid/", //<<- This is where I don't know how to put the DiagramId
type: "POST",
datatype: "json",
},
columns: [ // Definicion de columnas, ID's
{
data: "diagramaId", name: "diagramaId",
render: function (data) {
/* return "<a href='/DiagramaMaster/Details/" + data + "'>" + ("00000" + data).slice(-5) + "</a>"; */
return "<a href ='#WinModal' data-id='" + data + "' data-bs-toggle='modal' class='btnGrdDetails'>" + ("0000" + data).slice(-4) + "</a>";
}
}
],
// corte la definicion de columnas para efectos de que no se haga tan extenso
});
/* ******************** */
/* Dibujar la DataTable */
/* ******************** */
tableBase.draw()
});

Anyone can tell me whats wrong in here when im putting a array of number like :1,2 its starting to freeze the screen i hope someone can help me thanks

Hello guys im trying to learn vue and im trying to use datatable from https://datatables.net/ and having a problem with my action button that im not able to get the id when the #viewModal is been triggered i hope someone can help me to get the id of each buttons thanks and here is my code TIA:
EmployeeDataTable Component :
<template>
<div class="card">
<div class="card-header">
<div class="card-title">Employee List</div>
</div>
<div class="card-body">
<div class="table-responsive">
<table
id="employee-table"
class="table-sm table-bordered table-hover text-center display"
width="100%"
>
<thead>
<tr>
<th class="pt-3 pb-3">#</th>
<th>Name</th>
<th>Address</th>
<th>Contact #</th>
<th>Department</th>
<th>Status</th>
<th>Actions</th>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
</div>
</div>
</template>
<script>
//For Datatable to work
import "datatables.net";
import EmployeeEdit from "./EmployeeEdit.vue";
export default {
name: "EmployeeList",
data() {
return {
employees: [],
};
},
mounted() {
this.getEmployeeLists();
},
components: {
"employee-edit": EmployeeEdit,
},
methods: {
getEmployeeLists() {
// INITIALIZE DATATABLE
$("#employee-table")
.DataTable({
//LOADING
// processing: true,
//AJAX
serverSide: true,
//DIRECTION
order: [[1, "desc"]],
//AJAX
ajax: {
url: "/api/getEmployeeLists",
dataList: "json",
type: "POST",
data: { _token: "{{csrf_token()}}" },
},
//TABLE COLUMNS SHOULD BE THE SAME IN CONTROLLER
columns: [
{ data: "#" },
{ data: "name" },
{ data: "address" },
{ data: "contact" },
{ data: "department" },
{ data: "status" },
{
data: "actions",
//allowing modification
createdCell(cell, cellData, rowData) {
let EmployeeListDataTableActions = Vue.extend(
require("./EmployeeListDataTableAction.vue").default
);
let instance = new EmployeeListDataTableActions().$mount();
$(cell).empty().append(instance.$el);
},
},
],
//View Count in Table
lengthMenu: [
[10, 25, 50, -1],
[10, 25, 50, "All"],
],
})
.columns();
},
beforeDestroy: function () {
$(this.$el).DataTable().destroy();
},
},
};
</script>
EmployeeDataTableAction Component :
<template>
<button class="btn btn-primary btn-sm" #click="viewModal" title="View Employee Details">
<i class="fa fa-eye"></i>
</button>
</template>
<script>
export default{
name: 'EmployeeListDataTableAction',
data: function() {
return {
}
},
mounted() {
},
methods: {
viewModal() {
var id = $(this.$el).closest('tr').find('input').val();
return false;
axios
.post(`/api/getEmployeeDetails/${id}`, {
id: id,
})
.then((response) => {
$("#edit-employee-modal").modal("show");
$(".myModalLabel").text(
response.data.name +
" - " +
response.data.department_name
);
state.commit("getEmployeeDetailsArray", response.data);
state.commit("getTransactionId", response.data.id);
})
.catch((response) => {
this.$toast.top("Something went wrong!");
});
},
},
}
</script>
Employee Controller for the DataTable :
public function employeeList(Request $request){
$all = Employee::getEmployeeTotal();
//total count of data
$total_data = $all;
//total filter
$total_filtered = $total_data;
//set_time_limit(seconds)
$limit = $request->input('length');
//start
$start = $request->input('start');
//order
// $order = $columns[$request->input('order.0.column')];
//direction
$dir = $request->input('order.0.dir');
$search_value = $request->input('search.value');
if (!empty($search_value)) {
$posts = Employee::getEmployeeNameSearch($search_value,$start, $limit, $dir);
$total_data = count($posts);
$total_filtered = $total_data;
}else{
if(empty($request->input('search.value')))
{
//if no search
$posts = Employee::getEmployeeList($start, $limit, $dir);
}
}
$data = array();
if(!empty($posts))
{
$counter = $start + 1;
foreach ($posts as $post)
{
$department = GlobalModel::getSingleDataTable('departments',$post->department_id);
$status = StatusController::checkStatus($post->status);
$nested_data['#'] = '<span style="font-size: 12px ; text-align: center;">'.$counter++.'</span>';
$nested_data['name'] = '<p style="text-align: center;">'.$post->name.'</p>';
$nested_data['address'] = '<p style="text-align: center;">'.$post->address.'</p>';
$nested_data['contact'] = '<p style="text-align: center;">'.$post->contact.'</p>';
$nested_data['department'] = '<p style="text-align: center;">'.$department->name.'</p>';
$nested_data['status'] = '<p style="text-align: center;">'.$status.'</p>';
$nested_data['actions'] = '';
$data[] = $nested_data;
}
}
$json_data=array(
"draw" => intval($request->input('draw')),
"recordsTotal" => intval($total_data),
"recordsFiltered" => intval($total_filtered),
"data" => $data
);
return response()->json($json_data);
}
In the second line of your viewModal() function, you are placing a return false; statement. "The return statement ends function execution and specifies a value to be returned to the function caller." From Mozilla docs. That's why the API call is never executing.

Filter records using daterangetime picker

I have a target where I need to filter the data using daterange with time picker. The thing is I need to show the result of my filtered data based on what I selected on the said daterange with time picker I have provided my codes below and my target. Thank you so much in advance.
Views:
<div class="card-body table-responsive py-3 px-3">
<input type="text" id="demo" name="daterange" value="06/05/2021 - 06/06/2021" style="width:350px;">
<button class="btn btn-success float-right" onclick="add_person()" data-dismiss="modal"><i class="glyphicon glyphicon-plus"></i> Add Person</button>
<table id="table_account" class="table table-bordered table-hover" cellspacing="0">
<thead>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Username</th>
<th>Email</th>
<th>Mobile</th>
<th>Role</th>
<th>Status </th>
<!-- <th>File </th> -->
<th>Added By</th>
<th>Date Created</th>
<th>Date Updated</th>
<th>Updated By</th>
<th style="width:100x;">Action</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</script>
<thead>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Username</th>
<th>Email</th>
<th>Mobile</th>
<th>Role</th>
<th>Status </th>
<th>Added By</th>
<th>Date Created</th>
<th>Date Updated</th>
<th>Updated By</th>
<th style="width:100x;">Action</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
Ajax:
<script>
// first, put this at the top of your JS code.
let dateParams = {}
// update this with setting dataParams
$('#demo').daterangepicker({
"timePicker": true,
"timePicker24Hour": true,
"startDate": "06/05/2021",
"endDate": "06/06/2021",
locale: {
format: 'M/DD/YYYY hh:mm A'
}
}, function(start, end, label) {
// set the dateParam obj
dateParams = {
start: start.format('YYYY-MM-DD hh:mm'),
end: end.format('YYYY-MM-DD hh:mm')
}
console.log('New date range selected: ' + start.format('YYYY-MM-DD hh:mm') + ' to ' + end.format('YYYY-MM-DD hh:mm') + ' (predefined range: ' + start + + end +')');
});
$(document).ready(function() {
//datatables
table = $('#table_account').DataTable({
dom: 'lBfrtip',
buttons: [
'print', 'csv', 'copy', 'excel', 'pdfHtml5'
],
"processing": false, //Feature control the processing indicator.
"serverSide": true, //Feature control DataTables' server-side processing mode.
"order": [], //Initial no order.
// Load data for the table's content from an Ajax source
"ajax": {
"url": "<?php echo site_url('profile/ajax_list')?>",
"type": "POST",
"data": function (dateParams) {
return $.extend( { "start": dateParams.start,
"end": dateParams.end,}, dateParams, {
});
},
},
//Set column definition initialization properties.
"columnDefs": [
{
"targets": [ 0 ], //first column
"orderable": false, //set not orderable
},
{
"targets": [ -1 ], //last column
"orderable": false, //set not orderable
},
],
});
});
setInterval( function () {
table.ajax.reload(null,false);
}, 1000);
</script>
Controller:
public function ajax_list()
{
$list = $this->profiles->get_datatables();
$data = array();
$no = $_POST['start'];
foreach ($list as $person) {
$no++;
$row = array();
$row[] = $person->firstname;
$row[] = $person->lastname;
$row[] = $person->username;
$row[] = $person->email;
$row[] = $person->mobile;
$row[] = $person->role;
$row[] = $person->status;
$row[] = $person->addedBy;
$row[] = $person->dateCreated;
$row[] = $person->updatedBy;
$row[] = $person->dateUpdated;
//add html for action
$row[] = '<a class="btn btn-sm btn-primary" href="javascript:void(0)" title="Edit" onclick="edit_person('."'".$person->userID."'".')"><i class="glyphicon glyphicon-pencil"></i> Edit</a>';
$data[] = $row;
}
$output = array(
"draw" => $_POST['draw'],
"recordsTotal" => $this->profiles->count_all(),
"recordsFiltered" => $this->profiles->count_filtered(),
"data" => $data,
);
//output to json format
echo json_encode($output);
}
Model:
var $table = 'users';
var $column_order = array(null,'userID','firstname','lastname','username','email','mobile','addedBy','dateCreated');
var $order = array('userID' => 'desc');
var $column_search = array('email','firstname','lastname','username','email','mobile','dateCreated');
//set column field database for datatable orderable //set column field database for datatable searchable just firstname , lastname , address are searchable var $order = array('id' => 'desc'); // default order
private function _get_datatables_query()
{
if($this->input->post('daterange')){
$this->db->where('dateCreated >=', $this->input->post('start'));
$this->db->where('dateCreated <=', $this->input->post('end'));
}
// $this->input->post('start'); // YYYY-mm-dd
// $this->input->post('end'); // YYYY-mm-dd
$this->db->from($this->table);
$i = 0;
foreach ($this->column_search as $item) // loop column
{
if($_POST['search']['value']) // if datatable send POST for search
{
if($i===0) // first loop
{
$this->db->group_start(); // open bracket. query Where with OR clause better with bracket. because maybe can combine with other WHERE with AND.
$this->db->like($item, $_POST['search']['value']);
}
else
{
$this->db->or_like($item, $_POST['search']['value']);
}
if(count($this->column_search) - 1 == $i) //last loop
$this->db->group_end(); //close bracket
}
$i++;
}
if(isset($_POST['order'])) // here order processing
{
$this->db->order_by($this->column_order[$_POST['order']['0']['column']], $_POST['order']['0']['dir']);
}
else if(isset($this->order))
{
$order = $this->order;
$this->db->order_by(key($order), $order[key($order)]);
}
}
function get_datatables()
{
$this->_get_datatables_query();
if($_POST['length'] != -1)
$this->db->limit($_POST['length'], $_POST['start']);
$query = $this->db->get();
return $query->result();
}
To connect the calendar with the data output table, edit your daterangepicker initialization:
// first, put this at the top of your JS code.
let dateParams = {}
// update this with setting dataParams
$('#demo').daterangepicker({
"timePicker": true,
"timePicker24Hour": true,
"startDate": "06/05/2021",
"endDate": "06/06/2021",
locale: {
format: 'M/DD hh:mm A'
}
}, function(start, end, label) {
// set the dateParam obj
dataParams = {
start: start.format('YYYY-MM-DD'),
end: end.format('YYYY-MM-DD')
}
// reload the table
table.ajax.reload();
//console.log('New date range selected: ' + start.format('YYYY-MM-DD') + ' to ' + end.format('YYYY-MM-DD') + ' (predefined range: ' + label + ')');
});
Over in your DataTable() setup change your ajax to pass the start and end dates
"ajax": {
"url": "<?php echo site_url('profile/ajax_list')?>",
"type": "POST",
"data": function ( d ) {
// add this
return $.extend( {}, d, {
"start": dataParams.start,
"end": dataParams.end
});
// could also be written: return $.extend( {}, d, dataParams);
}
}
Finally, you'll need to pick this up in your CI app so you can search you DB.
$this->input->post('start'); // YYYY-mm-dd
$this->input->post('end'); // YYYY-mm-dd
Then this is just a nit. Please move <table id="table_account" class="table table-bordered table-hover" cellspacing="0"> to right above the first <thead>. Right now there is the datepicker element in between them. Might not matter, but it should be fixed.
https://datatables.net/reference/option/ajax

Resources