Just learning jquery\ajax will be very grateful for help!
I need to pass the date range that user choose (http://www.daterangepicker.com/) to a PAGE.PHP page for filtering, and return the data from PAGE.PHP. How can I send the date-range values to PAGE.PHP, without submit button, after user choose the data range?
Many thanks! My code is:
<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>
For example, you can do something like this:
$('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);
});
});
Don't forget about server-side validation and CSRF-protection.
You can use input change event and send an ajax request to your server like this:
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
Please note that you must verify your $startDate/$endDate
.
I hope this will help you.