2016-07-30 102 views
0

剛學習jquery \ ajax將非常感謝您的幫助!Daterangepicker,將數據範圍傳遞給page.php

我需要將用戶選擇的日期範圍(http://www.daterangepicker.com/) 傳遞到PAGE.PHP頁面進行過濾,並從PAGE.PHP返回數據。 如何在用戶選擇數據範圍之後將日期範圍值發送到PAGE.PHP,無需提交按鈕?

非常感謝! 我的代碼是:

<input type="text" name="datefilter" value="" />  
<script type="text/javascript"> 
$(function() { 

    $('input[name="datefilter"]').daterangepicker({ 
     autoUpdateInput: false, 
     locale: { 
      cancelLabel: 'Clear' 
     } 
    }); 

    $('input[name="datefilter"]').on('apply.daterangepicker', function(ev, picker) { 
     $(this).val(picker.startDate.format('MM/DD/YYYY') + ' - ' + picker.endDate.format('MM/DD/YYYY')); 
     // alert("A new date range was chosen:"); 
    }); 

    $('input[name="datefilter"]').on('cancel.daterangepicker', function(ev, picker) { 
     $(this).val(''); 
    }); 

}); 
</script> 

回答

1

例如,你可以這樣做:

$('input[name="datefilter"]').on('apply.daterangepicker', function(ev, picker) { 
     $.ajax({ 
      method: "POST", 
      url: "PAGE.PHP", 
      data: {startDate: picker.startDate, endDate: picker.endDate} 
     }).done(function(response){ 
      // Do something with response here 
      console.log(response); 
     }).fail(function (error) { 
      // And handle errors here 
      console.log(error); 
     }); 
     }); 

不要忘了服務器端驗證和CSRF保護。

+0

有了這個,你需要點擊'apply'才能發送數據!但操作系統聲明**沒有提交按鈕**:D –

+0

應用不等於submit =)在用戶選擇某個日期或按下應用按鈕後觸發此事件 –

+0

當然!但我認爲這就是OP的含義:D –

1

您可以使用輸入變化事件,併發送一個Ajax請求到服務器這樣的:

的Javascript:

$("#datefilter").change(function(e) { 
    if(!this.value) return; 
    var dates = this.value.split(" - "); 
    $.post('page.php', {startDate: dates[0], endDate: dates[1]}, function(data) { 
     //Show you data in the page 
     console.log(data); 
    }); 
}); 

PHP:

$startDate = strtotime($_POST['startDate']); 
$endDate = strtotime($_POST['endDate']); 
//You can format the date using date($format, $startDate|$endDate); 
//Make a query then echo the result that will be recieved by the ajax function 

請注意,您必須驗證您的$startDate/$endDate

我希望這會幫助你。

+0

謝謝伊斯梅爾! – VGranin