While the community has been helpful with my project, I still need a bit more assistance. Specifically, I'm trying to insert an Ajax array into a Javascript date range picker from a MySQL database, but it's not functioning as expected. Below is the code I am working with:
file #1 getdaterangepicker.php
<?php
include 'dbconfig.php';
$sql="SELECT start_date, end_date FROM date_ranges ";
$result = mysqli_query($conn,$sql);
// Initialize empty array.
$date_ranges = array();
// Populate the array.
while($row = mysqli_fetch_array($result)) {
// Create an associative array to hold the values.
array_push($date_ranges, array(
'start' => $row['start_date'],
'end' => $row['end_date']
));
mysqli_close($conn);
}
// Convert $date_ranges to JSON format.
$json = json_encode($date_ranges); // '[{"start": "2019-08-18", "end": "2019-08-19"}]'
echo $json;
?>
file 2 index.php:
// AJAX request function.
// Use this function to retrieve dates from the server.
function getDateRanges(callback) {
$.ajax({
url: 'getdaterangepicker.php',
method: 'GET',
dataType: 'html',
success: function(response) {
if (response) {
callback(response);
}
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(textStatus + ': ' + errorThrown);
}
});
}
getDateRanges(function(dates) {
$('input[name="start_date"]').daterangepicker({
autoUpdateInput: false,
locale: {
cancelLabel: 'Clear'
},
isInvalidDate: function(date) {
var dateRanges = [dates];
console.log(dates);
return dateRanges.reduce(function(bool, range) {
return bool || (date >= moment(range.start) && date <= moment(range.end));
}, false);
}
});
$('input[name="start_date"]').on('apply.daterangepicker', function(ev, picker) {
document.getElementById("start_date").value = picker.startDate.format('MM/DD/YYYY');
document.getElementById("end_date").value = picker.endDate.format('MM/DD/YYYY');
});
$('input[name="datefilter"]').on('cancel.daterangepicker', function(ev, picker) {
$(this).val('');
});
});
The javascript console displays the correct array (
[{"start":"2019-08-20","end":"2019-08-25"}]
), but the date picker isn't excluding the invalid dates. Strangely though, manually substituting var dateRanges = [dates];
with var dateRanges = [{"start": "2019-08-25", "end": "2019-08-31"}];
makes it work flawlessly. Any suggestions on why this might be happening? The date range picker in use can be found at: