I'm developing a holiday summer house rental website with a Jquery datepicker calendar that disables unavailable dates based on a MySQL query.
<?php
$datos = $con->query("SELECT * FROM bookings WHERE Status = 'Accepted' ");
?>
In order to calculate the disabled dates based on range of dates (checkin - checkout) I use a PHP code that calculates the dates in between and then puts those values in an array as follows:
<?php
while ($user = mysqli_fetch_array($datos)) {
?>
<?php
// Declare two dates
$Date1 = $user['Check_in'];
$Date2 = $user['Check_out'];
// Declare an empty array
$array = [];
// Use strtotime function
$Variable1 = strtotime($Date1);
$Variable2 = strtotime($Date2);
// Use for loop to store dates into array
// 86400 sec = 24 hrs = 60*60*24 = 1 day
for ($currentDate = $Variable1; $currentDate <= $Variable2;
$currentDate += (86400)) {
$Store = date('Y-m-d', $currentDate);
$array[] = $Store;}
// Display the dates in array format
$finalvalue = $array;
// Write it to the output
echo json_encode($finalvalue);?> <?php }?>
?>
$finalvalue outputs:
["2019-04-03","2019-04-04","2019-04-05","2019-04-06","2019-04-07",
"2019-04-08","2019-04-09","2019-04-10","2019-04-11", "2019-04-12","2019-04-13","2019-04-14"]
["2019-04-24","2019-04-25"]
////// Now in my JS for the datepickers:
var disabledDates = <?= json_encode($finalvalue)?>;
console.log(disabledDates)
////// for some reason finalvalue$ outputs only:
["2019-04-24","2019-04-25"]
$("#checkin").datepicker({
changeMonth: false,
dateFormat: 'yy-mm-dd',
defaultDate: new Date(),
minDate: new Date(),
beforeShowDay: function (date) {
var string = jQuery.datepicker.formatDate('yy-mm-dd', date);
return [disabledDates.indexOf(string) == -1]
},
prevText: '<i class="fa fa-chevron-left"></i>',
nextText: '<i class="fa fa-chevron-right"></i>',
onSelect: function (selected) {
$("#checkout").val(selected);
$("#checkout").datepicker("option", {minDate: new Date(selected)})
calcDiff();
}
});
Why isn't JS bringing the whole string of dates as in the PHP first output?
Could be that you are passing the variable in as a JSON encoded string but not parsing that data into a Javascript array? What if you did something like
var disabledDates = JSON.parse(<?= json_encode($finalvalue)?>);