I have the following code:
PHP (server):
if(isset($_POST['subdate']) && !empty($_POST['date'])) {
$daysOff = array();
$get_date = explode(',', $_POST['date']);
foreach ($get_date as $date) {
$date = explode('-', $date);
$day = $date[0];
$month = $date[1];
$year = $date[2];
$time_Stamp = mktime(0,0,0,$month,$day,$year);
$daysOff[] = strftime('%d-%m-%Y', $time_Stamp);
}
$daysOff = json_encode($daysOff);
echo "dates off: " .$daysOff;
}
else {
$daysOff = json_encode(array("23-09-2015", "15-09-2015"));
echo "dates off: " .$daysOff;
}
HTML (client)
...
<link rel="stylesheet" href="https://code.jquery.com/ui/1.11.4/themes/pepper-grinder/jquery-ui.css">
<script src="https://code.jquery.com/jquery-2.1.4.min.js"></script><scriptsrc="https://code.jquery.com/ui/1.11.4/jquery-ui.min.js"></script>
...
<form method="POST">
<input id="datepicker" type="date" name="date" autocomplete="off" readonly>
<br>
<input type="submit" name="subdate">
</form>
...
Javascript (client)
function datePicker() {
<?php echo "var datesOff = JSON.parse('" .$daysOff. "');"; ?>
var daysSelected = [];
var datepickerOpts = {
beforeShowDay: function(date){
var day = $.datepicker.formatDate('dd-mm-yy', date);
var checkDate = datesOff.indexOf(day);
if(checkDate == -1) {
// not found, data available
return [true, "", "available"];
}
else {
return [false, "", "not available"];
}
},
onSelect: function(date) {
var index = daysSelected.indexOf(date);
if(index == -1){
daysSelected.push(date);
console.log(daysSelected);
}
else {
daysSelected.splice(index, 1);
console.log(daysSelected);
}
$('input[type="date"]').val(daysSelected);
// prevent from closing datepicker when clicking date
$(this).data('datepicker')['inline'] = true;
},
onClose: function() {
$(this).data('datepicker')['inline'] = false;
},
dateFormat: 'dd-mm-yy',
showOn: "both",
buttonImage: "http://icons.iconarchive.com/icons/icons8/ios7/256/Time-And-Date-Calendar-icon.png",
buttonImageOnly: true,
buttonText: "Select date",
showAnim: "slideDown",
};
$('#datepicker').datepicker(datepickerOpts);
}
datePicker();
Everything works very well, starting from the principle that will not change manually the value of the input as shown in the image below, which causes a server error, more specifically with the function explode. I wanted to avoid this, I liked that there was a simple check (I've already tried with try / catch), eg if the inputs were this format: "dd-mm-aaa,dd-mm-aaaa"
is that we advance to explodes etc ... Keeping in mind that it must also result if there is only one date: "dd-mm-aaaa"
. Other suggestions for avoiding errors in this case are also welcome. Example of what happens:
Before submitting, manually change the value:
Aftersubmitting:
Errors arise when trying to access the indexes of $date
, within the cycle we have in the server side code.