datatable column filtering with serverside(ajax) doesn't work (with django) - javascript

I'm developing with django and javascript with datatable.
I want to apply column filtering in my datatable
(https://datatables.net/extensions/fixedheader/examples/options/columnFiltering.html)
but it works fine without serverside option & ajax (in client side),
but it doesn't work with serverside option & ajax.
How can i FIX IT? Please help me..
this is my code.
<table id="sample_table" class="table table-bordered table-hover">
<thead>
<tr>
<th class="sample_id">ID</th>
<th>date</th>
<th>serial</th>
<th>name</th>
<th>birth</th>
</tr>
</thead>
<tbody id="sample_table_body">
</tbody>
<tfoot>
<tr>
<th>ID</th>
<th>date</th>
<th>serial</th>
<th>name</th>
<th>birth</th>
</tr>
</tfoot>
</table>
</div>
<!-- /.card-body -->
</div>
var column_list = [
{ "data" : "id" , "className": "sample_id"},
{ "data" : "receiving_at" },
{ "data" : "serialnumber" },
{ "data" : "name" },
{ "data" : "birthday" },
];
$('#sample_table tfoot th').each(function(){
var title = $("#sample_table thead th").eq( $(this).index() ).text();
$(this).html('<input type="text" placeholder="Search '+title+'" />' );
});
var sample_table = $('#sample_table').DataTable({
"paging": true,
"autoWidth": false,
"lengthChange": false,
"ordering": true,
"processing" : true,
"columns": column_list,
"order": [ [0, 'desc'] ],
"fixedHeader": true,
"orderCellsTop": true,
"ajax": {
url: '/view_datatable/',
type: 'POST'
},
"serverSide" : true, //get data from server
"initComplete": function() { // column filtering RUN after table loaded .
$( '#sample_table tfoot input' ).on( 'keyup change clear', function () {
if ( sample_table.search() !== this.value && this.value.length>0) {
search_result = sample_table.search( this.value );
search_result.draw();
}
} );
}
});
#view.py
def list_datatable(request, companyname):
context = {}
if(request.method == "POST"):
start_page = int(request.POST['start'])
order_direction = request.POST["order[0][dir]"] # direction of ordering(asc, desc)
order_col_no = request.POST["order[0][column]"] # number of index to sort
order_col_name = request.POST['columns[' + str(order_col_no) + '][data]'].strip() # name of colum of ordering
sample_list_all = Sample.objects.all().order_by(order_col_name)
sample_list_per_page = []
for idx, obj in enumerate(sample_list_all[start_page:start_page + 10]):
data = {}
data['id'] = obj.id
data['receiving_at'] = str(obj.receiving_at)
data['birthday'] = obj.birthday
data['serialnumber'] = obj.serialnumber
data['name'] = obj.name
sample_list_per_page.append(data)
#-- end of --#
datalist_to_json = json.dumps(
{"data": sample_list_per_page, "recordsFiltered": len(sample_list_all), "recordsTotal": len(sample_list_all)}
)
return HttpResponse(datalist_to_json, content_type="application/json")

Related

How to create JS class and use of class object in Laravel 8?

Controller load the view and load the jQuery.
index.blade.php
<table id="UserGrid" class="table table-bordered table-striped">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Country</th>
<th>Dept</th>
<th>Title</th>
<th>Username</th>
<th>Role</th>
<th>Status</th>
<th>Created at</th>
<th>Action</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
#php
$pageJsScript = array(
'<script type = "text/javascript" src="js/setting/user/User_search.js")></script>'
);
$pageJsCalls = array(
'User_search.init();'
);
#endphp
The above code is in between the <section> tags
In my master page I call these functions:
<?php foreach ($pageJsScript as $jsScript)
{
echo $jsScript.PHP_EOL;
}
?>
<script>
jQuery(document).ready(function() {
Apps.init();
<?php foreach ($pageJsCalls as $jsCall)
{
echo $jsCall.PHP_EOL;
}
?>
});
</script>
And the then I created a separated file kept in JS folder:
var User_search = function () {
var DataGrid = $('#UserGrid');
var loadGridUrl = "{{url('/show_user_list')}}";
var dataTable = null;
var loadGrid = function () {
alert('called');
var url = loadGridUrl;
dataTable = DataGrid.DataTable({
dom: "Blfrtip",
aaSorting: [], //disabled initial sorting
ajax: url,
paging: true,
searching: true,
info: true,
processing: true,
serverSide: false,
lengthMenu: [[25, 50, 100, 200, 500], [25, 50, 100, 200, 500]],
pageLength: 25,
"columnDefs": [
{"width": "13%", "targets": 4, "class":'word-wrap'},
],
buttons: [
{extend: "csv"}
],
columns: [
//Table Column Header Collection
{data: "id"},
{data: "name"},
{data: "field_office"},
{data: "department"},
{data: "designation"},
{data: "email"},
{data: "role"},
//{data: "is_locked"},
{
data: null, render: function (data, type, row) {
if (data.is_locked == '1') {
return '<span class="label label-warning label-sm">Pending</span>';
}
else if (data.is_locked == '2') {
return '<span class="label label-success label-sm">Unlock</span>';
}
else if (data.is_locked == '3') {
return '<span class="label label-danger label-sm">Locked</span>';
}
}
},
{data: "created_at"},
{
data: null, render: function (data, type, row) {
// Combine the first and last names into a single table field
if(user_id==1 || user_id==21) {
return '<i class="fa fa-edit"></i> Edit' +
'| <i class="fa fa-trash-o"></i> Delete';
}else {
return '';
}
}
},
],
});
$("#UserGrid_tools > li > a.tool-action").on("click", function () {
var e = $(this).attr("data-action");
dataTable.button(e).trigger();
});
$(".dt-buttons").hide();
jQuery('#UserGrid_wrapper .dataTables_filter input').addClass("form-control input-small"); // modify table search input
jQuery('#UserGrid_wrapper .dataTables_length select').addClass("form-control input-small"); // modify table per page dropdown
jQuery('#UserGrid_wrapper .dataTables_length select').select2(); // initialize select2 dropdown
}
return {
//main function to initiate the module,
init: function () {
//Grid loading
if (!jQuery().dataTable) {
return;
}
loadGrid();
},
};
}();
Kindly guide me in order to get run all things, infact alert is working by the function loadGrid() is not working.

Two footers not printed in pdf and excel format when clicked in button in jquery datatable

Actaullay I have buttons to save in pdf and excel format.I have two footers coming from json as Total and Percentage.When i click the Button then only Total footer is coming but the Percentage row is not coming in the pdf and excel files.I need to show both the footer but it is not coming.
<table id="report46Table" class="display responsive nowrap" style="width: 100%">
<thead>
<tr>
<th>Disturbance</th>
<th>Zero</th>
<th>Minor</th>
<th>Medium</th>
<th>Major</th>
<th>Total</th>
<th>Occurance</th>
</tr>
</thead>
<tfoot>
<tr id="fTotal">
<th>Total</th>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
</tr>
<tr id="fPercentage">
<th>Total</th>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
</tr>
</tfoot>
</table>
script to load the datatable is:
<script>
$(document).ready(function() {
var report46Data = [];
var report46Footer = null;
var report46Table = $('#report46Table').DataTable({
data : report46Data,
dom: 'Bfrtip',
buttons: [
'copy',
{
extend: 'excel',
footer: true,
text : 'Export to Excel',
messageTop: 'Records of forest disturbances in the forest',
filename: function(){
return 'report46';
},
},
{
extend: 'pdfHtml5',
footer: true,
//orientation : 'landscape',
pageSize: 'TABLOID',
text : 'Export to Pdf',
messageTop: 'Records of forest disturbances in the forest',
title: '',
filename: function(){
return 'report46';
},
},
],
ordering: false,
"paging" :false,
columns : [ {
"data" : "disturbanceName"
}, {
"data" : "iZero"
}, {
"data" : "iMinor"
}, {
"data" : "iMedium"
} ,{
"data" : "iMajor"
},{
"data" : "total"
},{
"data" : "occurance"
}],
"footerCallback" : function(row, data, start, end, display) {
var api = this.api();
if (report46Footer) {
$($("#fTotal")[0].cells[0]).html(report46Footer[0].disturbance);
$($("#fTotal")[0].cells[1]).html(report46Footer[0].iZero);
$($("#fTotal")[0].cells[2]).html(report46Footer[0].iMinor);
$($("#fTotal")[0].cells[3]).html(report46Footer[0].iMedium);
$($("#fTotal")[0].cells[4]).html(report46Footer[0].iMajor);
$($("#fTotal")[0].cells[5]).html(report46Footer[0].total);
$($("#fTotal")[0].cells[6]).html("");
$($("#fPercentage")[0].cells[0]).html(report46Footer[1].disturbance);
$($("#fPercentage")[0].cells[1]).html(report46Footer[1].iZero);
$($("#fPercentage")[0].cells[2]).html(report46Footer[1].iMinor);
$($("#fPercentage")[0].cells[3]).html(report46Footer[1].iMedium);
$($("#fPercentage")[0].cells[4]).html(report46Footer[1].iMajor);
$($("#fPercentage")[0].cells[5]).html(report46Footer[1].total);
$($("#fPercentage")[0].cells[6]).html("");
}
}
});
$.ajax({
url : A_PAGE_CONTEXT_PATH + "/api/report46/all",
method : "GET",
dataType : "json",
success : function(response) {
report46Data = response.dataList;
report46Footer = response.footer;
report46Table.rows.add(report46Data).draw();
}
});
});
</script>

How to get all checkbox values in cells

I have jQuery datatables with some checkboxes for granting privileges.
I need to get table values to a array. Please enlighten me about how to get checkbox states inside cells, not only the checked ones. Thank you.
My table
<table id="jqueryTable" name="tt" class="table table-striped table-bordered" cellspacing="0">
<thead>
<tr>
<th name="id">
ID
</th>
<th name="name">
PRIV_Name_Str
</th>
<th name="create">
Create
</th>
<th>
Edit
</th>
<th>
View
</th>
</tr>
</thead>
<table>
My datatable query
function LoadProduct(element) {
$.ajax({
url: '/ADM_MAS_Privilege/GetFormData',
data: { YourValue: $('#productCategory').val() },
method: 'post',
dataType: 'json',
success: function (data) {
var table = $('#jqueryTable').dataTable({
paging: true,
sort: true,
searching: true,
scrollY: 200,
data: data,
bDestroy: true,
"columnDefs":
[{
"targets": [2, 3, 4],
"render": function (data, type, row, meta) {
console.log("XX " + meta.row + " " + meta.col);
return type === 'display' ?
'<input type="checkbox" id="p" class="chk" name="group' + meta.row + '" /> ' + data :
data;
columns: [{ "data": "ID", "ID": "ID", "autoWidth": true },
{
"data": "PRIV_Name_Str", "PRIV_Name_Str": "PRIV_Name_Str", "autoWidth": true
},
{
"data": "Create", "Create": "Create", "autoWidth": true
},
{ "data": "Edit", "Edit": "Edit", "autoWidth": true },
{
"data": "View"
}
]
});
}
});
};
My jQuery function to read datatable
$('#upload').click(function () {
var table = document.getElementById("jqueryTable");
var tableArr = [];
for (var i = 1; i < table.rows.length; i++) {
tableArr.push({
ID: table.rows[i].cells[0].innerHTML,
PRIV_Name_Str: table.rows[i].cells[1].innerHTML,
Create: table.rows[i].cells[2].innerHTML,
Edit: table.rows[i].cells[3].innerHTML,
View: table.rows[i].cells[4].innerHTML
});
}
});
I tried table.rows[i].cells[2].innerHTML.getElementById("p").checked even and it's not working.
Since you are using jQuery:
document.getElementById("jqueryTable").each(function (index, element) {
tableArr.push({
ID: element.cells[0].innerHTML,
PRIV_Name_Str: element.cells[1].innerHTML,
Create: element.cells[2].innerHTML,
Edit: element.cells[3].innerHTML,
View: element.cells[4].innerHTML
})
})
You can find the element and the checked property within each cell:
for (var i = 1; i < table.rows.length; i++) {
var cells = table.rows[i].cells;
tableArr.push({
ID: cells[0].innerHTML,
PRIV_Name_Str: cells[1].innerHTML,
Create: cells[2].querySelectorAll('input')[0].checked,
Edit: cells[3].querySelectorAll('input')[0].checked,
View: cells[4].querySelectorAll('input')[0].checked
});
}

Datatable return [Object Object] on index column

I'm using datatable to show data from controller (i'm using Codeigniter) and need to show number column on the left table column.
I have tried:
$(document).ready(function() {
$('#booking_table').dataTable( {
processing: true,
serverSide: true,
language: dt_lang,
pagingType: "simple",
dom: 't<"col-sm-3 text-left"l><"col-sm-3"i><"col-sm-2"r><"col-sm-4 text-right"p>',
autoWidth : true,
ajax: {
"url" : base_url+"book/ajax_history",
"type" : "POST",
data : function (d){
d.show_filter = $('#_show_filter').val();
d.view_type = $('#_view_type').val();
}
},
columns: [
{
data : "b.booking_id",
visible : false,
},
{ data : null}, //where i should put index number
{ data : 'b.booking_date', className : "hidden-xs"},
{ data : 'b.from_name', className : "hidden-xs"},
{ data : 'b.to_name'},
],
responsive: false
});
// reference the table in a variable
var table = $('#booking_table').DataTable();
table.on( 'order.dt search.dt', function () {
table.column(0, {
search:'applied',
order:'applied'
}).nodes().each( function (cell, i) {
cell.innerHTML = i+1;
} );
} ).draw();
My Table:
<table class="table table-condensed" id="booking_table">
<thead>
<tr>
<th class="hidden-xs">id</th>
<th>No</th>
<th class="hidden-xs">
Tanggal
</th>
<th class="hidden-xs">
Pengirim
</th>
<th>
Penerima
</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
Refer to this https://www.datatables.net/examples/api/counter_columns.html
but, it's not working. What am I doing wrong ?
Please try below mentioned solution. Hope this will help you. Actually you initialized datatable two times.
$(document).ready(function() {
var table = $('#booking_table').dataTable({
processing: true,
serverSide: true,
language: dt_lang,
pagingType: "simple",
dom: 't<"col-sm-3 text-left"l><"col-sm-3"i><"col-sm-2"r><"col-sm-4 text-right"p>',
autoWidth: true,
ajax: {
"url": base_url + "book/ajax_history",
"type": "POST",
data: function(d) {
d.show_filter = $('#_show_filter').val();
d.view_type = $('#_view_type').val();
}
},
columns: [{
data: "b.booking_id",
visible: false,
},
{
data: null
}, //where i should put index number
{
data: 'b.booking_date',
className: "hidden-xs"
},
{
data: 'b.from_name',
className: "hidden-xs"
},
{
data: 'b.to_name'
},
],
responsive: false
});
table.on('order.dt search.dt', function() {
table.column(0, {
search: 'applied',
order: 'applied'
}).nodes().each(function(cell, i) {
cell.innerHTML = i + 1;
});
}).draw();
});

DataTables hyperlink on all rows in a column

I am using DataTables to generate a table. There is a column containing order numbers.
For example:
...
I need every row in this column to have a hyperlink to view/order?id=? where ? is the contents of row in the Order No column. For example the first row would be a hyperlink to view/order?id=1321755 etc.
What is the simplest way I can do so?
Here is the code that I am using to initialize the DataTables:
<script type="text/javascript" charset="utf-8">
$(document).ready(function() {
$('#example').dataTable( {
"serverSide": true,
"ajax": {
"url": "../server_processing/orders.php",
"type": "POST"
},
"order": [[ 0, "desc" ]]
} );
} );
</script>
<table id="example" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>Order No</th>
...
</tr>
</thead>
<tbody>
</tbody>
</table>
Check this out:
http://datatables.net/reference/option/columns.render
You can add a column render callback when you specify columns definition.
var columnsDef = [
...
{
"title": "Order No.",
"render": function (data, type, row, meta) {
return '' + data + '';
}
},
...
];
$("#table").dataTable({
...
"columns": columnsDef,
...
});
The data in that column will be changed to what the render function return.
I needed to use jQuery dataTables and turn a normal field to be a HREF field.
Here you have it all, including also dataTables error handling..
Enjoy..
Yosi Lev
1) The HTML part:
<!-- COMPANIES LIST start -->
<div id="compListDiv" style="visibility:hidden; position : absolute; left : 360px; top : 40px;">
<br>
<table id="compList" align="left" border="1">
<thead>
<tr>
<th>id</th>
<th>name</th>
<th>address</th>
</tr>
</thead>
</table>
</div>
<!-- COMPANIES LIST end -->
2) The javascript dataTables part:
When a button is clicked the following js function is called:
function companiesList(){
accountstable=$('#compList').dataTable({
sort : true,
bFilter: false,
bInfo: false,
paging:false,
autoWidth: true,
ajax: {
url: "http://localhost:8080/j112/rest-1/companies/list",
dataType: 'json',
dataSrc: "data",
error: function ( xhr, textStatus, error ) {
if ( textStatus === 'timeout' ) {
alert( 'Timout error. The server took too long to send back the data.\nPlease try again.' );
}
else {
alert( 'User Not In Session.' );
location.href = "login.html";
}
myDataTable.fnProcessingIndicator( false );
}//function
}/* ajax: */,
scrollCollapse: true,
bDestroy: true,
serverSide:true,
fnRowCallback : function( nRow, aData, iDisplayIndex, iDisplayIndexFull ) { // this function is called for each row, but I could not use it to add the link
// if ( aData[1] == "A" )
//var td0 = $('td:eq(0)', nRow)[0];
// $('td:eq(0)', nRow).html( 'A');
// $('td:eq(0)', nRow).html( '<b>A</b>' )
},// fnRowCallback
initComplete : function(settings, json) { // this function is called after table is populated
//$("#compListDiv").show(); // this did not work so I used regular js to show the DIV
var d1 = document.getElementById('compListDiv');
d1.style.visibility = 'visible';
}, //initComplete
"columnDefs": [
{ "width": "10%", "targets": 0 },
{ "width": "20%", "targets": 0 },
{ "width": "70%", "targets": 0 }
],
"columns":[
//{"data" : "id"},
{ // render
"data": function (data, type, row, meta) {
return '' + data.id + '';
}
},
{"data" : "name"},
{"data" : "address"}
]
}); // dataTable()
}// companiesList()
By Yosi Lev - Feb 22, 2016

Categories

Resources