2017-07-15 91 views
0

我已经使用带有Ajax的Jquery Datatable创建了一个表,它工作得很好,我创建了一个daterangepicker来过滤数据表。使用Ajax将Daterangepicker参数传递给JQuery DataTable

<link href="./css/font-awesome.min.css" rel="stylesheet" type="text/css" /> 
 
\t <link rel="stylesheet" type="text/css" href="./css/daterangepicker-bs3.css" /> 
 
\t <script type="text/javascript" src="./js/daterangepicker.js"></script> 
 
\t <script type="text/javascript" src="./js/date.js"></script> 
 
\t <script type="text/javascript"> 
 
\t \t $(function() 
 
\t \t { 
 
\t \t \t var startdate = moment().subtract(29, 'days'); 
 
\t \t \t var enddate = moment(); 
 
\t \t \t function cb(startdate, enddate) { 
 
\t \t \t \t $('#reservation span').html(startdate.format('YYYY-MM-DD') + ' ~ ' + enddate.format('YYYY-MM-DD')); 
 
\t \t \t } 
 
\t \t \t $('#reservation').daterangepicker({ 
 
\t \t \t \t start: startdate, 
 
\t \t \t \t end: enddate, 
 
\t \t \t \t ranges: { 
 
\t \t \t \t 'Today': [moment(), moment()], 
 
\t \t \t \t 'Yesterday': [moment().subtract(1, 'days'), moment().subtract(1, 'days')], 
 
\t \t \t \t 'Last 7 Days': [moment().subtract(6, 'days'), moment()], 
 
\t \t \t \t 'Last 30 Days': [moment().subtract(29, 'days'), moment()], 
 
\t \t \t \t 'This Month': [moment().startOf('month'), moment().endOf('month')], 
 
\t \t \t \t 'Last Month': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')] 
 
\t \t \t \t } 
 
\t \t \t }, cb); 
 
\t \t \t cb(startdate, enddate); 
 
\t \t }); 
 
\t </script> 
 
    
 

 
\t <script src="./js/jquery-1.12.4.js" type="text/javascript"></script> 
 
\t <script src="./js/jquery.dataTables.min.js" type="text/javascript"></script> 
 
\t <link rel="stylesheet" href="./css/jquery.dataTables.min.css" type="text/css" /> 
 
\t <script type="text/javascript" charset="utf-8"> 
 
\t \t $(document).ready(function() 
 
\t \t { 
 
\t \t \t // DataTable 
 
    \t \t \t $('#Show-Tables').DataTable({ 
 
\t \t \t \t "processing": true, 
 
\t \t \t \t "serverSide": true, 
 
\t \t \t \t "pagingType": "full_numbers", 
 
\t \t \t \t "ajax": { 
 
\t \t \t \t \t "url": "dt-json-data.php", 
 
\t \t \t \t \t "type": "POST", 
 
\t \t \t \t \t "dataSrc": "records" 
 
\t \t \t \t }, 
 
\t \t \t \t "columns": [ 
 
\t \t \t \t \t { "data": "Tanggal" }, 
 
\t \t \t \t \t { "data": "CustomerNo" }, 
 
\t \t \t \t \t { "data": "CustomerName" }, 
 
\t \t \t \t \t { "data": "Branch" }, 
 
\t \t \t \t \t { "data": "Tot_Menit" }, 
 
\t \t \t \t \t { "data": "Tot_call" } 
 
\t \t \t \t ], 
 
\t \t \t \t "autoWidth": true 
 
\t \t \t }); 
 
\t \t }); 
 
\t </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 
 
\t 0 => 'Tanggal', 
 
\t 1 => 'CustomerNo', 
 
\t 2 => 'CustomerName', 
 
\t 3 => 'Branch', 
 
\t 4 => 'Tot_Menit', 
 
\t 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 
 
\t $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') "; 
 
\t $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 
 
\t $nestedData=array(); 
 

 
\t foreach($row as $index=>$value) { 
 
\t \t $nestedData[$index] = $value; 
 
\t } 
 

 
\t $data[] = $nestedData; 
 
} 
 

 
$json_data = array(
 
\t \t \t "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. 
 
\t \t \t "recordsTotal" => intval($totalData), // total number of records 
 
\t \t \t "recordsFiltered" => intval($totalFiltered), // total number of records after searching, if there is no searching then totalFiltered = totalData 
 
\t \t \t "records"   => $data // total data array 
 
\t \t \t); 
 
//print_r($data); 
 

 
echo json_encode($json_data); // send data as json format 
 

 
?>
<html> 
 
<body> 
 

 
<form action="#" method="post" name="niceform" class="form-horizontal"> 
 
<div id="daterange" class="pull-left" style="margin-left: 15px"> 
 
\t \t \t \t <div id="reservation" class="input-prepend" style="background: #fff; cursor: pointer; padding: 5px 10px; border: 1px solid #ccc; width: 100%"> 
 
\t \t \t \t \t <i class="glyphicon glyphicon-calendar fa fa-calendar"></i>&nbsp; 
 
\t \t \t \t \t <span></span> <b class="caret"></b> 
 
\t \t \t \t </div> 
 
\t \t \t </div> 
 
\t \t \t <div class="pull-right" style="margin-right: 15px"> 
 
\t \t \t \t <input name="Submit" type="submit" value="Ok" class="btn btn-facebook" /> 
 
\t \t \t </div> 
 
</form> 
 

 
\t \t \t <div class="box-body"> 
 
\t \t \t \t <div class="table-responsive"> 
 
\t \t \t \t \t <table class="display" id="Show-Tables" width="100%"> 
 
\t \t \t \t \t \t <thead> 
 
\t \t \t \t \t \t \t <tr align="center"> 
 
\t \t \t \t \t \t \t \t <th><center>Tanggal</center></th> 
 
\t \t \t \t \t \t \t \t <th><center>Customer No.</center></th> 
 
\t \t \t \t \t \t \t \t <th><center>Customer Name</center></th> 
 
\t \t \t \t \t \t \t \t <th><center>Branch</center></th> 
 
\t \t \t \t \t \t \t \t <th><center>Total Menit</center></th> 
 
\t \t \t \t \t \t \t \t <th><center>Total Call</center></th> 
 
\t \t \t \t \t \t \t </tr> 
 
\t \t \t \t \t \t </thead> 
 
\t \t \t \t \t </table> 
 
\t \t \t \t </div> 
 
\t \t \t </div> 
 

 
</body> 
 
</html>

我怎么能传递daterangepicker值筛选我的DataTable?

回答

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. 
+0

嗨Bindrid,你的建议还没有在我的脚本上工作。我尝试了你的建议时有一些错误(我为你抓住了它,请看一看)。 –

+0

它可能是一个时间问题。我认为数据表正在尝试访问日期范围对象,然后才能完成构建 – Bindrid