I am using data table to display large number of rows from database.I was using below code to display data fetched from database but as data started increasing,it takes lots of time to load as there are multiple joins in select query.
Below is the code which takes lots of time to load view:
<script>
$(document).ready(function() {
$('#fileData').dataTable({
"aLengthMenu": [[5,10, 25, 50, 100, -1], [5,10, 25, 50, 100, "All"]],
//"aaSorting": [[ 4, "desc" ]],
"iDisplayLength": <?php echo 5; ?>,
'bProcessing' : true,
'bServerSide' : false,
"oTableTools": {
"sSwfPath": "assets/media/swf/copy_csv_xls_pdf.swf",
"aButtons": []
},
"oLanguage": {
"sSearch": "Filter: "
},
"aoColumns": [
null,
null,
null,
null,
null,
null,
null,
null,
null,
null
],
"aoColumns": [
{"bVisible": true},
{"bVisible": true},
{"bVisible": true},
{"bVisible": true},
{"bVisible": true},
{"bVisible": true},
{"bVisible": true},
{"bVisible": true},
{"bVisible": true},
{"bVisible": true},
{"bVisible": true}
]
}).columnFilter({ aoColumns: [
{ type: "text", bRegex:true },
{ type: "text", bRegex:true },
{ type: "text", bRegex:true },
{ type: "text", bRegex:true },
{ type: "text", bRegex:true },
{ type: "text", bRegex:true },
{ type: "text", bRegex:true },
{ type: "text", bRegex:true },
{ type: "text", bRegex:true },
{ type: "text", bRegex:true },
{ type: "text", bRegex:true }
]});
});
</script>
<table id="fileData" class="table table-striped table-bordered table-hover table-full-width">
<thead>
<tr>
<th>Sl.No</th>
<th>Type</th>
<th>No </th>
<th>0-15 yrs M</th>
<th>0-15 yrs F</th>
<th>15-45 yrs M</th>
<th>15-45 yrs F</th>
<th>Above 45 yrs M</th>
<th>Above 45 yrs F</th>
<th>Cumulative Since April</th>
<th>Remarks</th>
</tr>
</thead>
<tbody>
<?php //if(is_object($proj_workers_report)) {
?>
<?php foreach ($nreports->result() as $index=>$row) { ?>
<tr>
<td> <?php echo $index + 1; ?> </td>
<td><?php echo $row->test1; ?></td>
<td><?php echo $row->test2; ?></td>
<td><?php echo $row->test3; ?></td>
<td><?php echo $row->test4; ?></td>
<td><?php echo $row->test5; ?></td>
<td><?php echo $row->test; ?></td>
</td>
<td></td>
</tr>
<?php
} ?>
</tbody>
</table>
After searching for solution to reduce loading time i found solution as enabling "serverSide":true.so i changed the code as below
$(document).ready(function () {
var year="<?php echo base_url() . 'reportc/new_disease_morbidity_report'; ?>";
alert(year);
var dataTable = $('#example2').DataTable({
"processing":true,
"serverSide":true,
"order":[[ 0, "desc" ]],
"ajax":{
url:"<?php echo base_url() . 'test/nreport'; ?>",
type:"POST",
data:"{'id':year}",
success: function (data) {
alert("success");
},
error: function () {
alert('error');
}
},
'language': {
"emptyTable":"No patient available"
},
"columnDefs":[
{
//"targets":[0, 3],
//"orderable":false,
},
],
});
controller:
function new_disease_morbidity_report()
{
$year = $this->input->post('id');
echo $year;
}
But issue with new code is that it is unable to call function in controller.can anyone help me out with this issue.Is there something i am missing ?
Just by adding "serverSide": true you are telling Datatable let me handle Pagination
In order to do so Datatable will append few request parameter in request API and in response you need to set few parameter to let Server Side pagination work smoothly.
You are on right track. Just need to implement correctly.
Note: As Datatable will append few parameter you need to handle them at your controller level. Add those parameters as #RequestParam. Inspect your API call to get exact parameters.
1 Datatable will add following parameter in your request POST/GET
order: asc
start: 20
length: 10
This will help you in passing LIMIT parameter in DB Query.
SELECT * FROM User LIMIT 20,10;
2 Your API should return following fields in addition
"draw": 3, // unique ID
"recordsTotal": 57, // total number of records
"recordsFiltered": 57 // total number of filtered records
You can see a sample demo here Please inspect and check request and response
Refer this answer for more detail.
Related
I Have used this ignited_datatables https://github.com/IgnitedDatatables/Ignited-Datatables in my CodeIgniter project. It successfully returns data from the database. But the main problem is that when I add a new record the newly inserted data is not shown in the table automatically and when I refresh the page then the newly inserted data is then shown in the table. so I want to show that data automatically through ajax and I have not to refresh the page.
My View
<div class="box-body table-responsive">
<table id="Slider_table" class="table table-bordered table-hover">
<thead>
<tr>
<th>ID</th>
<th>Title</th>
<th>item_Price</th>
<th>Description</th>
<th>Status</th>
<th>Action</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div><!-- /.box-body -->
This Script is Inside the View
$(document).ready(function() {
$("#Slider_table").dataTable( {
"bProcessing": true,
"bServerSide": true,
"sAjaxDataProp": "data",
"fnServerData": function(sSource, aoData, fnCallback){
$.ajax({
"dataType": "json",
"type" : "POST",
"url" : "'.base_url().'Home/items_list/list",
"data" : aoData,
"success" : function(res){
fnCallback(res);
}
});
}
});
});
I think you need to use draw() method after success in order to have the table's display updated.
table.row.add( {
//you dynamic data
"name": "Tiger Nixon",
"position": "System Architect",
"salary": "$3,120",
"start_date": "2011/04/25",
"office": "Edinburgh",
"extn": "5421"
} ).draw();
as per documentation. please refer draw()
You can use ajax.reload() method
var i=1;
function datatable()
{
$("#myTable1").dataTable().fnDestroy();
$('#myTable1').DataTable({
"ordering": true,
"searching": true,
"bPaginate": true,
ajax: 'myajaxURL.php',
columns : [
{ "render": function ( data, type, full, meta ) { return i++; }
},
{"data": "col1"},
{"data": "col2"},
{"data": "col3"},
]
});
}
function insertData {
//after each insertion do this
var i=1;
$('#myTable1').DataTable().ajax.reload();
//after each insertion do this
}
$(document).ready(function () {
datatable();
});
i always did this in every view of my page
var table;
table = $('#Slider_table').dataTable({
"bPaginate": false,
"bLengthChange": false,
"bFilter": false, // OPTIONAL
"bSorting": false,
"bInfo": true,
"bAutoWidth": false,
});
function getData() {
$.ajax({
type: "POST",
url: "<?php echo base_url('your_controler/function_name'); ?>",
data: aoData,
error: function(response) {
alert('Error')
},
success: function(response) {
setTable(response);
}
});
}
function setTable(response) {
var obj = JSON.parse(response);
var t = $('#Slider_table').dataTable();
t.clear().draw();
$.each(obj, function(index, value) {
var a = value.a;
var b = value.b;
var c = value.c;
t.row.add([
a,
b,
c
]).draw(false);
})
}
So everytime you reload or insert a new data,you just have to call getData() function to load a new set of data you just insert. And t.clear().draw(); will clear all data from tbody,and replaced it with new one . Hope this helps
I am getting this error:
DataTables warning: table id=discount_html - Requested unknown parameter '0' for row 0. For more information about this error, please see http://datatables.net/tn/4
My code is:
$('#abcd').DataTable({
"processing":true,
"serverSide":true,
"destroy" : true,
"order":[],
"pageLength": 50,
"columnDefs": [
{ "orderable": false, "targets": 0 }
],
"ajax":{
url: 'abc.php',
type:"POST",
"data": function(d){
var frm_data = $('form').serializeArray();
$.each(frm_data, function(key, val) {
d[val.name] = val.value;
});
},
dataSrc: function (json) {
var return_data = new Array();
if(json.data.length > 0){
var obj = json.data;
console.log(obj);
return obj;
}
return return_data;
},
"columns" : [
{'data':'input'},
{'data': 'date'},
{'data': 'id'},
{'data': 'pname'},
{'data': 'cname'},
{'data': 'clname'},
{'data': 'dname'},
{'data': 'act'}
]
},
});
This is my AJAX response:
"draw":1,
"recordsTotal":1073,
"recordsFiltered":1073,
"data":[
{
"input":"<input data-id = "0" type="checkbox" name="report[]" class="allCheck" value="1234">",
"date":"2018-01-29",
"id":"1244",
"pname":"XYZ",
"cname":"adasdasd",
"clname":"NA",
"dname":"asdasdasdas",
"act":"hgh"
},
{
"input":"<input data-id = "1" type="checkbox" name="report[]" class="allCheck" value="23232">",
"date":"2018-01-29",
"id":"23232",
"pname":"aaaaa",
"cname":"asdasdsadasdsa",
"clname":"ewqweqewq",
"dname":"aaaaaaaa",
"act":"hgh"
},
and below is the HTML:
<tr>
<th><input type="checkbox" name="" id="checkAll"></th>
<th class="recept_td01">Date </th>
<th class="recept_td03">Code</th>
<th class="recept_td04">Name</th>
<th class="recept_td05">Ce</th>
<th class="recept_td05">Cli</th>
<th class="recept_td06">Doc</th>
<th class="recept_td07" id="action">Action</th>
</tr>
What am I doing wrong, that I am getting that error, tried everything but nothing seems to be working.
I need to make a table dynamically with DataTable Jquery, the table must be Server-side processing type and in the same request (Ajax) and answer the columns are made and obviously the results.
DatosColumna=""//Json with Response of ajax
$('#table_query_info').dataTable({
columnDefs: DatosColumna,//Here its the headers
destroy: true,
processing: true,
serverSide: true,
ajax: {
url: myBaseUrl + "consults/find_docs",
type: "post",
data: function (d) {
d.datos = make_info()//Send Json with info
},
statusCode: {
200: function (resp) {
alert("OK");//That Good
}
}
}
});
I tried with this code but it has not worked
Thank you very much
steps for resolution:
make a html code
<table class="table" id="tablaindex" style="width:100%"></table>
Obtengo las columnas, antes de inicializar la tabla
$.ajax({
type: "POST",
url: "AtencionTurno/ColumnasDatatable",
data: TblOficina,
success: function (response) {
inicializarTabla(response);
}, error: function (request, status, error) {
console.log("Error");
}
});
The reques obtain the follow json
[
{
"title": "Column 1",
"data": "Id_Turno",
"orderable": false
},
{
"title": "Column 2",
"data": "Turno",
"orderable": false
},
{
"title": "Column 3",
"data": "Clasificacion",
"orderable": false
},
{
"title": "Column 4",
"data": "Concepto",
"orderable": false
},
{
"title": "Column 5",
"data": "Hora",
"orderable": false
}]
now I initialize the table with the columns that were obtained
inicializarTabla = function (columnas) {
var dataTable = $('#tablaindex').DataTable({
"processing": true,
"serverSide": true,
stateSave: true,
orderable: false,
"order": [],
columns: columnas,
"lengthChange": false,
searching: false,
colReorder: false,
"ajax": {
url: "AtencionTurno/IndexTurnos",
type: "post",
data: TblOficina
}
});
};
response from server:
{
"draw": "1",
"recordsTotal": 4,
"recordsFiltered": 4,
"data": [
{
"Id_Turno": "358",
"Turno": "ALAT1",
"Clasificacion": "euismod",
"Concepto": "Convallis",
"Hora": "11:00:12",
"Tiempo_Espera": "2018/07/03 11:00:12",
"Tipo_Cliente": "Calendario",
"Transferencia": "",
"null": "358"
},
{
"Id_Turno": "354",
"Turno": "ALAK23",
"Clasificacion": "euismod",
"Concepto": "Pagos",
"Hora": "16:36:14",
"Tiempo_Espera": "2018/06/29 16:36:14",
"Tipo_Cliente": "Utiles Escolares ",
"Transferencia": "",
"null": "354"
}
]
}
I am using the follwing version of datatables:
<script src="https://cdn.datatables.net/r/bs-3.3.5/jqc-1.11.3,dt-1.10.8/datatables.min.js"></script>
And the following version of Editor, Buttons and Select:
<script type="text/javascript" src="/jquery/Editor-PHP-1.5.5/js/dataTables.editor.js"></script>
<script src="https://cdn.datatables.net/buttons/1.1.2/js/dataTables.buttons.min.js"></script>
<script src="https://cdn.datatables.net/select/1.1.2/js/dataTables.select.min.js"></script>
This is my js file which calls my API and reads into Datatables and Editor:
var editor; // use a global for the submit and return data rendering in the examples
$(document).ready(function() {
editor = new $.fn.dataTable.Editor( {
ajax: {
create: {
type: 'POST',
url: '../php/rest/create.php'
},
edit: {
type: 'PUT',
url: '../php/rest/edit.php?id=_id_'
},
remove: {
type: 'DELETE',
url: '../php/rest/remove.php?id=_id_'
}
},
table: "#list_blogs_table",
fields: [ {
label: 'entry_id',
name: 'entry_id'
},
{
label: 'entry_name',
name: 'entry_name'
},
{
label: 'entry_body',
name: 'entry_body'
},
{
label: 'entry_date',
name: 'entry_date'
},
{
label: 'status',
name: 'status'
},
{
label: 'created_timestamp',
name: 'created_timestamp'
},
{
label: 'updated_timestamp',
name: 'updated_timestamp'
},
]
} );
$('#list_blogs_table').DataTable( {
dom: "Bfrtip",
url: "http://www.example.com/api/v1/blog/blogs/format/json",
dataSrc: "message",
columns: [
{ data: "entry_id" },
{ data: "entry_name" },
{ data: "entry_body" },
{ data: "entry_date" },
{ data: "status" },
{ data: "created_timestamp" },
{ data: "updated_timestamp" },
],
select: true,
buttons: [
{ extend: "create", editor: editor },
{ extend: "edit", editor: editor },
{ extend: "remove", editor: editor }
]
} );
} );
This is my HTML:
<table id="list_blogs_table" class="table table-hover table-striped table-bordered">
<thead>
<tr>
<th>Id</th>
<th>Title</th>
<th>Article Text</th>
<th>entry_date</th>
<th>Status</th>
<th>Created</th>
<th>Updated</th>
</tr>
</thead>
<tfoot>
<th>Id</th>
<th>Title</th>
<th>Article Text</th>
<th>entry_date</th>
<th>Status</th>
<th>Created</th>
<th>Updated</th>
</tfoot>
<tbody>
</tbody>
</table>
Here is my JSON file (have shortened it)
{
"status": "success",
"message": [{
"entry_id": "1",
"entry_name": "12345678",
"entry_body": "this is just the beginning update",
"entry_date": "2016-05-02 20:13:12",
"status": "active",
"created_timestamp": "2016-05-01 21:25:51",
"updated_timestamp": "2016-05-01 21:25:51"
}, {
"entry_id": "2",
"entry_name": "one one one",
"entry_body": "this is just the beginning update 1",
"entry_date": "2016-05-02 20:13:16",
"status": "active",
"created_timestamp": "2016-05-02 14:44:03",
"updated_timestamp": "2016-05-01 21:25:51"
},
[snip]
Unfortunately, I get a table with no data as following
I found the solution. Here is the revised code. Silly over looking things.
$('#list_blogs_table').DataTable( {
dom: "Bfrtip",
"ajax": {
"url": "http://www.example.com/api/v1/blog/blogs/format/json",
"dataSrc": "message",
},
columns: [
{ data: "entry_id" },
{ data: "entry_name" },
{ data: "entry_body" },
{ data: "entry_date" },
{ data: "status" },
{ data: "created_timestamp" },
{ data: "updated_timestamp" },
],
select: true,
buttons: [
{ extend: "create", editor: editor },
{ extend: "edit", editor: editor },
{ extend: "remove", editor: editor }
]
} );
I'm trying to use DataTables with php and mysql. I have an ajax call that is pulling in data as such:
[
{
"id": 3,
"ptid":"blah",
"last_name":"blah",
"first_name":"blah",
"priv_application":"E",
"priv_document":"E",
"priv_note":"E",
}
]
I'm configuring DataTables with the following:
$('#listing').DataTable( {
"paging": false,
"searching": false,
"select": true,
ajax: {
url: '{{ url("administration/admindata") }}',
dataSrc: ''
},
columns: [
{ title: "ID" },
{ title: "PtID" },
{ title: "Last Name" },
{ title: "First Name" },
{ title: "Application" },
{ title: "Documents" },
{ title: "Notes" }
]
});
And the HTML for the table is as follows:
<table id="listing" class="display" width="100%"></table>
However, it doesn't want to load the data even though this configuration is exactly like the first example given here:
https://datatables.net/manual/ajax
I'm getting the following error:
DataTables warning: table id=listing - Requested unknown parameter '0' for row 0, column 0. For more information about this error, please see http://datatables.net/tn/4
Any assistance is greatly appreciated.
When using array of objects as your data source, you need to specify data source for each column using columns.data option.
$('#listing').DataTable( {
"paging": false,
"searching": false,
"select": true,
"ajax": {
"url": '{{ url("administration/admindata") }}',
"dataSrc": ''
},
columns: [
{ data: "id", title: "ID" },
{ data: "ptid", title: "PtID" },
{ data: "last_name", title: "Last Name" },
{ data: "first_name", title: "First Name" },
{ data: "priv_application", title: "Application" },
{ data: "priv_adocument", title: "Documents" },
{ data: "priv_note", title: "Notes" }
]
});
Try something like this.
ajax": {
type': 'POST',
'url': "<?=action('TestController#postTestfunction')?>"
},
try to use the ajax call without blade template code.
and make sure your route is written something like this.
Route::controller('test', 'TestController');
Also try with change your controller function name "admindata" to "postAdmindata"
Let me know still if you get stuck anywhere.