I’m trying to populate a select dropdown with the hours that don’t have appointments booked, and right now I’m experiencing somethin really dumb with datepicker, because I want it to be populated based on the selected doctor in the selected day, but it seems to not even recognize that a day has been selected When I do select it.
This is my AJAX call
<script>
$(document).ready(function(){
$('#datepicker').datepicker({
onSelect: function() {
setTimeout(triggerAjaxCall, 0);
}
});
$('#selMedico').change(function(){
triggerAjaxCall();
});
function triggerAjaxCall() {
var doctor = $('#selMedico').val();
var date = $('#datepicker').val();
console.log('Doctor:', doctor);
console.log('Date:', date);
if (!doctor || !date) {
console.log('Doctor or date not selected');
return;
}
// AJAX call
$.ajax({
type: 'POST',
url: 'fetchConsultas.php',
data: { medico: doctor, dia: date },
dataType: 'json',
success: function(response) {
console.log('AJAX request successful');
console.log('Response:', response);
$('#hora').empty();
$.each(response, function(index, value) {
$('#hora').append('<option value="' + value + '">' + value + '</option>');
});
},
error: function(jqXHR, textStatus, errorThrown) {
console.log('AJAX request failed:', textStatus, errorThrown);
}
});
}
});
</script>
and this is my fetchConsultas.php file
<?php
if (isset($_POST['medico']) && isset($_POST['dia'])) {
$medicoSelecionado = $_POST['medico'];
$dataSelecionada = $_POST['dia'];
include 'connection.php';
$stmt = $pdo->prepare('SELECT id_hora
FROM tabconsultas
WHERE id_medico = ?
AND id_dia = ? ;');
$stmt->execute([$medicoSelecionado, $dataSelecionada]);
$horarios = $stmt->fetchAll(PDO::FETCH_COLUMN, 0);
// Create an array of all the hours from 08:00:00 to 18:00:00 (excluding 13:00:00)
$allHours = [];
for ($i = 8; $i <= 18; $i++) {
if ($i != 13) {
$hour = str_pad($i, 2, '0', STR_PAD_LEFT) . ':00:00';
$allHours[] = $hour;
}
}
// Get the hours that are not in the result of the query
$availableHours = array_diff($allHours, $horarios);
echo json_encode($availableHours);
$pdo = null;
$stmt = null;
} else {
echo "No doctor or date selected.";
}
die();
I’m pretty sure that there’s something wrong with the datepicker plugin itself, but I’m not very experienced, so I’m hoping someone can help me find out a way to go over this.
Note: It actually populates the dropdown correctly If I :
- select a doctor and then select a date, then select another random doctor and finally go back to the doctor selected at first.
Just like what’s happening here: