I'm working with Datatables server-side processing in OctoberCMS.
Everything works fine but search input doesn't work.
Search input works fine as I tried it in client-side processing.
Datatables part Javascript
$(document).ready(function() {
var tableId = "datalist";
var table = $('#' + tableId).DataTable({
processing: true,
serverSide: true,
ajax: {
url: '/ajax?tb={{ tableName|raw() }}&fd={{ fields|raw() }}',
type: 'GET',
//tb: 'BYAPPS_apps_data',
error: function(e) {
console.log(e);
}
},
paging: true,
pageLength: 50,
"info": false,
"autoWidth": true,
"fixedHeader": false,
"responsive": true,
"orderClasses": false,
"stateSave": true,
"dom": 'Bfrtip',
"buttons": [
'excel', 'copy'
],
});
$('.dataTables_filter input').bind('keyup', function () {
console.log('here');
table.search(this.value).draw();
});
});
Ajax part PHP file
function onStart()
{
$table = $_GET['tb'];
$length = $_GET['length'];
$start = $_GET['start'];
$fields = explode("|", $_GET['fd']);
$result = DB::table($table)->skip($start)->limit($length)->get();
$data = array();
foreach($result as $row) {
$sub_array = array();
for ($i = 0; $i < count($fields); $i++) {
$sub_array[] = $row->{$fields[$i]};
}
$data[] = $sub_array;
}
$output = array(
"draw" => intval($_GET['draw']),
"recordsTotal" => DB::table($table)->count(),
"recordsFiltered" => DB::table($table)->count(),
"data" => $data,
);
echo json_encode($output);
}
How can I fix this and make the search input work?
Related
나의 코드 입니다..
<script>
var dataTable;
$(document).ready(function(){
// Initialize datatable
dataTable = $('#empTable').DataTable({
dom: 'Blfirtp',
"lengthMenu": [
[10, 50, 100, 500, '-1'],
[10, 50, 100, 500, "All"]
],
'buttons': [
{
extend: 'csv',
exportOptions: {
columns: [1,2,3,4,5]
}
},
{
extend: 'excel',
exportOptions: {
columns: [1,2,3,4,5]
}
}
],
'processing': true,
'serverSide': true,
'serverMethod': 'post',
'ajax': {
'url':'ajaxfile.php',
'data': function(data){
// Read values
data.request = 1;
}
},
'columns': [
{ data: 'action' },
{ data: 'emp_name' },
{ data: 'email' },
{ data: 'gender' },
{ data: 'salary' },
{ data: 'city' }
],
'columnDefs': [ {
'targets': [0], // column index (start from 0)
'orderable': false, // set orderable false for selected columns
}]
});
// Check all
$('#checkall').click(function(){
if($(this).is(':checked')){
$('.delete_check').prop('checked', true);
}else{
$('.delete_check').prop('checked', false);
}
});
// Delete record
$('#delete_record').click(function(){
var deleteids_arr = [];
// Read all checked checkboxes
$("input:checkbox[class=delete_check]:checked").each(function () {
deleteids_arr.push($(this).val());
});
// Check checkbox checked or not
if(deleteids_arr.length > 0){
// Confirm alert
var confirmdelete = confirm("Do you really want to Delete records?");
if (confirmdelete == true) {
$.ajax({
url: 'ajaxfile.php',
type: 'post',
data: {request: 2,deleteids_arr: deleteids_arr},
success: function(response){
dataTable.ajax.reload();
}
});
$('#checkall').prop('checked', false);
}
}
});
});
// Checkbox checked
function checkcheckbox(){
// Total checkboxes
var length = $('.delete_check').length;
// Total checked checkboxes
var totalchecked = 0;
$('.delete_check').each(function(){
if($(this).is(':checked')){
totalchecked+=1;
}
});
// Checked unchecked checkbox
if(totalchecked == length){
$("#checkall").prop('checked', true);
}else{
$('#checkall').prop('checked', false);
}
}
</script>
</body>
</html>
Datatables, There is no problem when writing the initial function, but when it is added more and more, if you suddenly select all, not work
Hi there,
i have a table with over 8.000 entries (until now, data will rise in future). In some cases i have to export all of them to Excel, therefor i set the lengthMenu to:
Plain text
"lengthMenu": [[10, 25, 50, 250, -1], [10, 25, 50, 250, "All"]],
It works fine until i use the "All" statement. With "All" i get the following error:
Unable to get property 'length' of undefined or null reference
Can anybody help me? Normally it makes no sense to show all 8.000 entries on the webpage, but i have to export them all to Excel. Perhaps someone knows a better way.
이것은 ajaxfile.php
<?php
include 'config.php';
$request = $_POST['request'];
// Datatable data
if($request == 1){
## Read value
$draw = $_POST['draw'];
$row = $_POST['start'];
$rowperpage = $_POST['length']; // Rows display per page
$columnIndex = $_POST['order'][0]['column']; // Column index
$columnName = $_POST['columns'][$columnIndex]['data']; // Column name
$columnSortOrder = $_POST['order'][0]['dir']; // asc or desc
$searchValue = mysqli_real_escape_string($con,$_POST['search']['value']); // Search value
## Search
$searchQuery = " ";
if($searchValue != ''){
$searchQuery .= " and (emp_name like '%".$searchValue."%' or
email like '%".$searchValue."%' or
city like'%".$searchValue."%' ) ";
}
## Total number of records without filtering
$sel = mysqli_query($con,"select count(*) as allcount from employee");
$records = mysqli_fetch_assoc($sel);
$totalRecords = $records['allcount'];
## Total number of records with filtering
$sel = mysqli_query($con,"select count(*) as allcount from employee WHERE 1 ".$searchQuery);
$records = mysqli_fetch_assoc($sel);
$totalRecordwithFilter = $records['allcount'];
## Fetch records
$empQuery = "select * from employee WHERE 1 ".$searchQuery." order by ".$columnName." ".$columnSortOrder." limit ".$row.",".$rowperpage;
$empRecords = mysqli_query($con, $empQuery);
$data = array();
while ($row = mysqli_fetch_assoc($empRecords)) {
$data[] = array(
"action"=>"<input type='checkbox' class='delete_check' id='delcheck_".$row['id']."' onclick='checkcheckbox();' value='".$row['id']."'>",
"emp_name"=>$row['emp_name'],
"email"=>$row['email'],
"gender"=>$row['gender'],
"salary"=>$row['salary'],
"city"=>$row['city'],
);
}
## Response
$response = array(
"draw" => intval($draw),
"iTotalRecords" => $totalRecords,
"iTotalDisplayRecords" => $totalRecordwithFilter,
"aaData" => $data,
);
echo json_encode($response);
exit;
}
// Delete record
if($request == 2){
$deleteids_arr = $_POST['deleteids_arr'];
foreach($deleteids_arr as $deleteid){
mysqli_query($con,"DELETE FROM employee WHERE id=".$deleteid);
}
echo 1;
exit;
}
?>
I create tables using datatables, and data from MySQL. I want to add string data to data in my table, for example for data in columns the temperature of each data is (C) as shown below. How do I add strings like ° C and % to my table?
PHP code:
<?php
//fetch.php
$connect = mysqli_connect("localhost", "root", "", "db_hosting");
//$columns = array('order_id', 'order_customer_name', 'order_item', 'order_value', 'order_date');
$columns = array('id', 'time', 'temperature', 'humidity');
$query = "SELECT id, DATE_FORMAT(time, '%d %M %Y %H:00') AS time, temperature, humidity FROM data WHERE ";
if($_POST["is_date_search"] == "yes")
{
$query .= 'DATE(time) BETWEEN "'.$_POST["start_date"].'" AND "'.$_POST["end_date"].'" AND ';
}
if(isset($_POST["search"]["value"]))
{
$query .= '
(id LIKE "%'.$_POST["search"]["value"].'%")
';
}
if(isset($_POST["order"]))
{
$query .= "GROUP BY DATE_FORMAT(time, '%d-%M-%Y %H:00') ORDER BY 'time'";
}
$query1 = '';
if($_POST["length"] != -1)
{
$query1 = 'LIMIT ' . $_POST['start'] . ', ' . $_POST['length'];
}
$number_filter_row = mysqli_num_rows(mysqli_query($connect, $query));
$result = mysqli_query($connect, $query . $query1);
$data = array();
while($row = mysqli_fetch_array($result))
{
$sub_array = array();
$sub_array[] = "";
$sub_array[] = $row["time"];
$sub_array[] = $row["temperature"];
$sub_array[] = $row["humidity"];
$data[] = $sub_array;
}
function get_all_data($connect)
{
$query = "SELECT * FROM data";
$result = mysqli_query($connect, $query);
return mysqli_num_rows($result);
}
$output = array(
"draw" => intval($_POST["draw"]),
"recordsTotal" => get_all_data($connect),
"recordsFiltered" => $number_filter_row,
"data" => $data
);
echo json_encode($output);
?>
Table:
<table width="98%" class="table table-bordered table-striped" id="tabel_data" style="text-align:center;">
<thead >
<tr >
<th style="text-align:center;" width="8%">No.</th>
<th style="text-align:center;" width="22%">Datetime</th>
<th style="text-align:center;" width="18%">Temp (°C)</th>
<th style="text-align:center;" width="18%">Humidity (%)</th>
</tr>
</thead>
Javacript code (dataTable):
in javascript, there is a code to filter data based on date and can export table data
$(document).ready(function(){
$('.input-daterange').datepicker({
todayBtn:'linked',
format: "yyyy-mm-dd",
autoclose: true
});
fetch_data('no');
function fetch_data(is_date_search, start_date='', end_date='')
{
var dataTable = $('#tabel_data').DataTable({
"columnDefs": [ {
"searchable": false,
"orderable": false,
"targets": 0,
} ],
"order": [[ 1, 'asc' ]],
dom: 'Bfrtip',
buttons: [
{
extend: 'print',
title: '<h3 align ="center">Data table</h3>',
text: '<i class="fa fa-l fa-print"></i> Print',
titleAttr: 'Cetak Tabel',
messageTop: '<p align ="center">created by PDFmake</p>',
filename: 'data_table'
},
{
extend: 'pdfHtml5',
customize: function (doc) {
doc.content[1].table.widths =
Array(doc.content[1].table.body[0].length + 1).join('*').split('');
doc.defaultStyle.alignment = 'center';
doc.styles.tableHeader.alignment = 'center';
doc.content.splice(0, 1, {
text: [{
text: 'Data Table \n',
bold: true,
fontSize: 16
}, {
text: ' Created by PDFmake \n', //
bold: true,
fontSize: 11
},],
margin: [0, 0, 0, 12],
alignment: 'center'
});
},
exportOptions: {
modifier: {
selected: null
}
},
title: 'Data table',
titleAttr: 'Simpan sebagai PDF',
text: '<i class="fa fa-l fa-file-pdf-o"></i> PDF',
filename: 'data_tabel_'
}
],
"paging": false,
"processing" : true,
"serverSide" : true,
bFilter:false,
"ajax" : {
url:"fetch.php",
type:"POST",
data:{
is_date_search:is_date_search, start_date:start_date, end_date:end_date
},
}
});
dataTable.on('draw.dt', function () {
var info = dataTable.page.info();
dataTable.column(0, { search: 'applied', order: 'applied', page: 'applied', }).nodes().each(function (cell, i) {
cell.innerHTML = i + 1 + info.start;
dataTable.cell(cell).invalidate('dom');
});
});
}
$('#search').click(function(){
var start_date = $('#start_date').val();
var end_date = $('#end_date').val();
if(start_date != '' && end_date !='')
{
$('#tabel_data').DataTable().destroy();
fetch_data('yes', start_date, end_date);
//$("#tabel").show();
document.getElementById('tabel').style.display = "block";
}
else
{
alert("Both Date is Required");
}
});
});
you can create your table in JD by String:
String ="<th style="text-align:center;" width="18%">"+(variable)+"(°C)</th>"
You can wrap the content into <span>'s and do it in pure CSS:
Renderer:
columnDefs: [{
targets: [2,3],
render: function(data) {
return '<span>'+data+'</span>'
}
}]
CSS:
table.dataTable td:nth-child(3) span:after {
content: ' ℃';
color: red;
font-size: 80%;
}
table.dataTable td:nth-child(4) span:after {
content: ' %';
color: red;
font-size: 80%;
}
The benefit of this approach is that the data still is considered as numbers-
demo -> http://jsfiddle.net/1du07tfn/
I have a solution to the problem
PHP:
$data = array();
$celcius = ' °C';
$percent = ' %';
while($row = mysqli_fetch_array($result))
{
$sub_array = array();
$sub_array[] = "";
$sub_array[] = $row["time"];
$sub_array[] = $row["temperature"].$celcius;
$sub_array[] = $row["humidity"].$percent;
$data[] = $sub_array;
}
This question already has answers here:
how to use Jquery Datatables Ellipsis renderer for template field link button?
(1 answer)
Solution for Ellipsis - Jquery + Bootstrap + Datatables
(1 answer)
DataTables how to cut string and add (...) and put the full string in tooltip
(2 answers)
Closed 4 years ago.
I'm working on a CI project that requires the use of datatables, some of the content in the database has a large number of characters and i want to limit those to 150, i have tried to use the examples that are posted in the datatables site without luck, just to be clear i didn´t made this full script, I took it from somewhere else.
This is my script
<script type="text/javascript">
$(document).ready(function() {
var st = $('#search_type').val();
var table = $('#consulta-table').DataTable({
"dom" : "<'row'<'col-sm-12'tr>>" +
"<'row'<'col-sm-5'i><'col-sm-7'p>>",
"processing": false,
"pagingType" : "full_numbers",
"pageLength" : 15,
"serverSide": true,
"orderMulti": false,
"order": [
<?php if($default_order != null) : ?>
[<?php echo $default_order ?>, "<?php echo $default_order_type ?>"]
<?php else : ?>
[6, "desc"]
<?php endif; ?>
],
"columns": [
null,
null,
null,
null,
null,
{ "orderable": false },
{ "orderable": false },
null,
{ "orderable": false }
],
"ajax": {
url : "<?php echo site_url("consultas/consultas_page/" . $page . "/" . $catid) ?>",
type : 'GET',
data : function ( d ) {
d.search_type = $('#search_type').val();
}
},
"drawCallback": function(settings, json) {
$('[data-toggle="tooltip"]').tooltip();
}
});
$('#form-search-input').on('keyup change', function () {
table.search(this.value).draw();
});
} );
function change_search(search)
{
var options = [
"search-like",
"search-exact",
"title-exact",
"title2-exact",
"title3-exact",
"title4-exact",
"title5-exact",
"title6-exact",
];
set_search_icon(options[search], options);
$('#search_type').val(search);
$( "#form-search-input" ).trigger( "change" );
}
function set_search_icon(icon, options)
{
for(var i = 0; i<options.length;i++) {
if(options[i] == icon) {
$('#' + icon).fadeIn(10);
} else {
$('#' + options[i]).fadeOut(10);
}
}
}
</script>
Any help is appreciated
Thanks in advance
Have you tried this yet? It is the official plugin offered by people under the datatables.net community. You just need to follow the instruction there and you're good to go.
Simply download/copy the plugin script then, follow this sample code
$('#myTable').DataTable( {
columnDefs: [ {
targets: 0,
render: $.fn.dataTable.render.ellipsis()
} ]} );
I am fetching records from database and converting data into json array. I am getting json response correctly. but table shows no entry in my view.. please see once . Thanks.
my controller
function test() {
$list = $this->get_data_model->get_apartment_details();
$data = array();
$no = $_POST['start'];
foreach ($list as $apartments) {
$no++;
$row = array();
$row[] = $no;
$row[] = $apartments->a_id;
$row[] = $apartments->a_name;
$data[] = $row;
}
$output = array(
"draw" => 5,
"recordsTotal" => 2,
"recordsFiltered" => 1,
"data" => $data
);
echo json_encode($output);//
}
my view
<section class="tab-pane fade in active" id="newPanel">
<table style='width:100%'' class='table' id='example'>
<thead>
<tr>
<th> ID </th>
<th> Name </th>
<th> Activate </th>
<th> Edit </th>
</tr>
</thead>
</table>
</section>
my ajax call
$('#example').DataTable( {
"processing" : true,
"serverSide" : true,
"ajax" : {
"type" : "POST",
"url": "<?php echo base_url("apartments/test");?>",
"dataSrc" : ""
},
"columns": [
{ "data": "a_id"},
{ "data": "a_name" }
],
"dom": 'Bfrtip',
"buttons": [
{
"extend": 'copyHtml5',
"exportOptions": {
"columns": ':contains("Office")'
}
},
'excelHtml5',
'csvHtml5',
'pdfHtml5'
]
} );
} );
Your Table ID attribute and your ajax call id attribute is different. hope below code will help you.
$('#newPanel').DataTable( {
"processing" : true,
"serverSide" : true,
"ajax" : {
"type" : "POST",
"url": "<?php echo base_url("apartments/test");?>",
"dataSrc" : ""
},
"columns": [
{ "data": "a_id"},
{ "data": "a_name" }
],
"dom": 'Bfrtip',
"buttons": [
{
"extend": 'copyHtml5',
"exportOptions": {
"columns": ':contains("Office")'
}
},
'excelHtml5',
'csvHtml5',
'pdfHtml5'
]
} );
} );
Hey Guys I have a problem. I`m new to Cassandra and DataTables and my task is to send data from our 'Cassandra-Server' to the Table plug-in 'DataTables'.
I was looking for some examples or tutorials but I never found one for Cassandra-NoSQL.
I tried the following and this Error is always occurring:
PHP:
//setting header to json
header('Content-Type: application/json');
include 'connect.php';
$statement = new Cassandra\SimpleStatement("SELECT * FROM table1");
$result = $session->execute($statement);
//loop through the returned data
$data = array();
foreach ($result as $row) {
$data[] = $row;
}
//now print the data
print json_encode($data);
JS:
$(document).ready(function () {
'use strict';
var table = $('#main').DataTable({
"processing": true,
"serverSide": true,
"ajax": {
"url": "php/server-side.php",
"type": "GET"
},
"columns": [
{ "data": "name" },
{ "data": "type1" },
{ "data": "type2" },
{ "data": "type3" },
{ "data": "land" },
{
"data": "id",
"orderable": false
}
],
"order": [[0, 'asc']]
});
});
Error:
*Uncaught TypeError: Cannot read property 'length' of undefined
jquery.dataTables.min.js: 39*
I think DataTables don't know what to do with the information (json/$data).
In this example https://datatables.net/examples/data_sources/server_side.html
sspclass.php is used but it is written in SQL so no use for me =(
Can somebody help me with this specific problem?