我使用带有Ajax的Jquery Datatable创建了一个表,它工作得很好,我创建了一个daterangepicker来过滤数据表。
<link href="./css/font-awesome.min.css" rel="stylesheet" type="text/css" />
<link rel="stylesheet" type="text/css" href="./css/daterangepicker-bs3.css" />
<script type="text/javascript" src="./js/daterangepicker.js"></script>
<script type="text/javascript" src="./js/date.js"></script>
<script type="text/javascript">
$(function()
{
var startdate = moment().subtract(29, 'days');
var enddate = moment();
function cb(startdate, enddate) {
$('#reservation span').html(startdate.format('YYYY-MM-DD') + ' ~ ' + enddate.format('YYYY-MM-DD'));
}
$('#reservation').daterangepicker({
start: startdate,
end: enddate,
ranges: {
'Today': [moment(), moment()],
'Yesterday': [moment().subtract(1, 'days'), moment().subtract(1, 'days')],
'Last 7 Days': [moment().subtract(6, 'days'), moment()],
'Last 30 Days': [moment().subtract(29, 'days'), moment()],
'This Month': [moment().startOf('month'), moment().endOf('month')],
'Last Month': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')]
}
}, cb);
cb(startdate, enddate);
});
</script>
<script src="./js/jquery-1.12.4.js" type="text/javascript"></script>
<script src="./js/jquery.dataTables.min.js" type="text/javascript"></script>
<link rel="stylesheet" href="./css/jquery.dataTables.min.css" type="text/css" />
<script type="text/javascript" charset="utf-8">
$(document).ready(function()
{
// DataTable
$('#Show-Tables').DataTable( {
"processing": true,
"serverSide": true,
"pagingType": "full_numbers",
"ajax": {
"url": "dt-json-data.php",
"type": "POST",
"dataSrc": "records"
},
"columns": [
{ "data": "Tanggal" },
{ "data": "CustomerNo" },
{ "data": "CustomerName" },
{ "data": "Branch" },
{ "data": "Tot_Menit" },
{ "data": "Tot_call" }
],
"autoWidth": true
});
});
</script>
<?php
//Here is my code for dt-json-data.php file :
/* Database connection start */
$servername = "xxx.xxx.xxx.xxx";
$username = "xxxx";
$password = "*******";
$dbname = "*****";
$conn = mysqli_connect($servername, $username, $password, $dbname) or die("Connection failed: " . mysqli_connect_error());
/* Database connection end */
// storing request (ie, get/post) global array to a variable
$requestData= $_REQUEST;
$columns = array(
// datatable column index => database column name
0 => 'Tanggal',
1 => 'CustomerNo',
2 => 'CustomerName',
3 => 'Branch',
4 => 'Tot_Menit',
5 => 'Tot_call'
);
// getting total number records without any search
$sql = "SELECT * "; //intensionaly * to fetch all columns
$sql.=" FROM Tot_cdr_all";
$query = mysqli_query($conn, $sql);
$totalData = mysqli_num_rows($query);
$totalFiltered = $totalData; // when there is no search parameter then total number rows = total number filtered rows.
$sql = "Select Tanggal,CustomerNo,CustomerName,Branch,sum(Tot_Menit) as Tot_Menit,sum(Tot_call) as Tot_call From Tot_cdr_all WHERE 1=1";
if( !empty($requestData['search']['value']) ) { // if there is a search parameter, $requestData['search']['value'] contains search parameter
$sql.=" AND DATE_FORMAT(Tanggal,'%Y-%m-%d') BETWEEN DATE_FORMAT('%".$requestData['search']['value']."%','%Y-%m-%d') AND DATE_FORMAT('%".$requestData['search']['value']."%','%Y-%m-%d') ";
$sql.=" OR ( UPPER(CustomerName) like UPPER('%".$requestData['search']['value']."%') OR UPPER(Branch) like UPPER('%".$requestData['search']['value']."%') OR UPPER(CustomerNo) like UPPER('%".$requestData['search']['value']."%') ) ";
}
$sql.=" GROUP BY 1,2,3,4";
$query = mysqli_query($conn, $sql);
$totalData = mysqli_num_rows($query);
$sql.=" ORDER BY 1,3 LIMIT ".(empty($requestData['start']) ? 0 : $requestData['start']).", ".$requestData['length']." ";
$query = mysqli_query($conn, $sql);
$totalFiltered = $totalData; // when there is a search parameter then we have to modify total number filtered rows as per search result.
$data = array();
while( $row=mysqli_fetch_assoc($query) ) { // preparing an array
$nestedData=array();
foreach($row as $index=>$value) {
$nestedData[$index] = $value;
}
$data[] = $nestedData;
}
$json_data = array(
"draw" => intval( $requestData['draw'] ), // for every request/draw by clientside , they send a number as a parameter, when they recieve a response/data they first check the draw number, so we are sending same number in draw.
"recordsTotal" => intval( $totalData ), // total number of records
"recordsFiltered" => intval( $totalFiltered ), // total number of records after searching, if there is no searching then totalFiltered = totalData
"records" => $data // total data array
);
//print_r($data);
echo json_encode($json_data); // send data as json format
?>
&#13;
<html>
<body>
<form action="#" method="post" name="niceform" class="form-horizontal">
<div id="daterange" class="pull-left" style="margin-left: 15px">
<div id="reservation" class="input-prepend" style="background: #fff; cursor: pointer; padding: 5px 10px; border: 1px solid #ccc; width: 100%">
<i class="glyphicon glyphicon-calendar fa fa-calendar"></i>
<span></span> <b class="caret"></b>
</div>
</div>
<div class="pull-right" style="margin-right: 15px">
<input name="Submit" type="submit" value="Ok" class="btn btn-facebook" />
</div>
</form>
<div class="box-body">
<div class="table-responsive">
<table class="display" id="Show-Tables" width="100%">
<thead>
<tr align="center">
<th><center>Tanggal</center></th>
<th><center>Customer No.</center></th>
<th><center>Customer Name</center></th>
<th><center>Branch</center></th>
<th><center>Total Menit</center></th>
<th><center>Total Call</center></th>
</tr>
</thead>
</table>
</div>
</div>
</body>
</html>
&#13;
如何通过daterangepicker值来过滤我的数据表?
答案 0 :(得分:0)
我在我的环境中重新创建了你的日期范围,但做了一个小改动。 我添加了一个数据范围更改事件来强制数据表运行ajax。
<script type="text/javascript">
$(function()
{
var startdate = moment().subtract(29, 'days');
var enddate = moment();
function cb(startdate, enddate) {
$('#reservation span').html(startdate.format('YYYY-MM-DD') + ' ~ ' + enddate.format('YYYY-MM-DD'));
这个cb函数是一个回调函数,所以我认为这是导致你的问题。没有办法保证第一次调用和数据表ajax调用之间的时间。
由于每次更改日期时都会调用此函数,因此我删除了事件处理程序并使用它来触发数据表ajax调用。
$('#example').DataTable().draw();
}
$('#reservation').daterangepicker({
start: startdate,
end: enddate,
ranges: {
'Today': [moment(), moment()],
'Yesterday': [moment().subtract(1, 'days'), moment().subtract(1, 'days')],
'Last 7 Days': [moment().subtract(6, 'days'), moment()],
'Last 30 Days': [moment().subtract(29, 'days'), moment()],
'This Month': [moment().startOf('month'), moment().endOf('month')],
'Last Month': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')]
}
}, cb)
如上所述,我删除了我最初放在这里的事件处理程序。
cb(startdate, enddate);
});
</script>
但是因为我们想要传递日期,即使其他内容,例如在搜索框中输入的文本,我实际上并没有在该事件处理程序中传递日期。我在数据表ajax调用中获取日期。
<script type="text/javascript" charset="utf-8">
$(document).ready(function()
{
// DataTable
$('#Show-Tables').DataTable( {
"processing": true,
"serverSide": true,
我添加了延迟加载。这意味着创建了数据表,但第一次获取数据的调用被延迟,直到被其他一些操作触发。这样可以在获取数据之前创建日期选择器时间。
"deferLoading":0,
"pagingType": "full_numbers",
"ajax": {
"url": "dt-json-data.php",
"type": "POST",
//// Addded section to get the dates based on daterangepicker documentation
data: function (dtParms) {
var start = $('#reservation').data('daterangepicker').startDate.format();
var end = $('#reservation').data('daterangepicker').endDate.format();
// I put the dates in the search object but you can put it where you want inside the object.
dtParms.search.startDate = start;
dtParms.search.endData = end;
return dtParms;
},
"dataSrc": "records"
},
"columns": [
{ "data": "Tanggal" },
{ "data": "CustomerNo" },
{ "data": "CustomerName" },
{ "data": "Branch" },
{ "data": "Tot_Menit" },
{ "data": "Tot_call" }
],
"autoWidth": true
});
});
</script>I tested this against my environment so make sure I did not make misstates to make it fit yours.