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;
}
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'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?
I have the below part of code which works on my local machine but not on the server.
When I execute it on the server then am getting an error as "Uncaught SyntaxError: Unexpected token ;"
<?php
$checkValue = array();
$i= 0;
while ($row = mysql_fetch_array($searchdetails)) {
$checkValue[$i][] = $row['ID'];
$checkValue[$i][] = $row['1'];
$checkValue[$i][] = $row['2'];
$checkValue[$i][] = $row['3'];
if(#$row['4'] == "NULL" || #$row['4'] == NULL) {
$checkValue[$i][] = "NULL";
}else{
$sql = "SELECT * FROM Class WHERE ID_Class =".#$row['4'];
$data = mysql_query( $sql );
$class = mysql_fetch_assoc($data);
$checkValue[$i][] = $class['Class'];
}
if(#$row['5'] == "NULL" || #$row['5'] == NULL) {
$checkValue[$i][] = "NULL";
}else{
$sql = "SELECT * FROM Place WHERE ID_Place =".#$row['5'];
$data = mysql_query( $sql );
while($row1 = mysql_fetch_array($data)) {
$checkValue[$i][] = $row1['1'];
}
}
$i++;
}
?>
<script>
var grid;
var columns = [
{ id: "switch", name: "switch", field: "switch", formatter: imageFormatter, sortable: true },
{ id: "college", name: "college", field: "college", width: 50 },
{ id: "Number", name: "Number", field: "Number", width: 50 },
{ id: "Class", name: "Class", field: "Class",sortable: true },
{ id: "Place", name: "Place", field: "Place", width: 40 },
];
$(function () {
var MS_PER_DAY = 24 * 60 * 60 * 1000;
var data = [];
**var listdata = <?php echo json_encode($checkValue);?>;**
console.log(listdata);
for (var i = 0; i < listdata.length; i++) {
data[i] = {
switch: listdata[i][0],
college: listdata[i]['1'],
Number: listdata[i]['2'],
Strength: listdata[i]['3'],
Place: listdata[i]['4'],
};
}
})
</script>
I tried this after searching for different answers in Stackoverflow
var listdata = <?php echo json_encode($checkValue)?>;
but still it doesn't work.
What might be the issue thats stopping it here. Any help on this is much more appreciated!!
EDIT: I identified the reason, The table class has some Spanish characters in it and so it is not displaying the data. How to overcome with these characters?
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'
]
} );
} );
I am using DataTables in one of my projects in which I have to fill it with the Oracle query results. I am referring to this document.
Problem:
All the 10 columns returned by query get displayed in row 1 column 1 of the table.
Javascript
$('#inquiryForm').submit(function(){
var cnic = "data="+ $( "#cnicInd" ).val();
//alert(cnic);
$.ajax({
type: "POST",
url: "php/inquiryInd.php",
data: cnic,
success: function(datapage) {
//$("#errmsg").html(data).show();
var datacopy = [[datapage]];
prompt("Result",datacopy);
$('#dataTables-example').DataTable({
responsive: true,
"data": datacopy,
columns: [
{ title: "Policy No." },
{ title: "Client Name" },
{ title: "Gross Premium" },
{ title: "Next Due Date" },
{ title: "Commencement Date" },
{ title: "Cash Value" },
{ title: "Total Amount Paid" },
{ title: "Total Amount Due" },
{ title: "Total unconsumed Amount" },
{ title: "Status" }
]
});
}
});
$('#searchTable').show();
return false;
});
inquiryInd.php
while (($row = oci_fetch_array($stmnt)) != false) {
$result = "";
$result .= '"'.$row['PROPOSAL']."\"";
$result .= ',"'.$row['FULLNAME']."\"";
$result .= ',"'.$row['GROSSPREMIUM']."\"";
$result .= ',"'.$row['NEXTDUEDAT']."\"";
$result .= ',"'.$row['COMMENDATE']."\"";
$result .= ',"'.$row['CASH_VALUE']."\"";
$result .= ',"'.$row['TOTAL_AMOUNT_PAID']."\"";
$result .= ',"'.$row['TOTAL_AMOUNT_DUE']."\"";
$result .= ',"'.$row['TOTAL_AMOUNT_DUE']."\"";
$result .= ',"'.$row['STATUS']."\"";
//$result .= ']';
$dataset .= $result;
//Something like "Tiger Nixon", "System Architect", "Edinburgh", "5421", "2011/04/25", "$320,800"
}
Please let me know what am I doing wrong. Any help will be highly appreciated.