I am using Jquery datepicker to highlight specific dates. Dates are being fetched from the database in PHP and MySQL. Dates will be fetched depending on the selected value in the select tag. The dates are successfully fetched and shown in the console.
If I fetch all the dates in the script directly then it shows the highlighted dates. But when I use select tag and send the selected value through ajax then it doesn't.
Jquery:
<script>
$(function() {
// An array of dates
var eventDates = {};
$("#select").on("change", function() {
var truck = $(this).val();
$.ajax({
url: 'ajax/vehicledate.php',
type: "POST",
/*contentType: "application/json; charset=utf-8",*/
data: {
val: truck
},
success: function(data) {
console.log(data);
}
});
// datepicker
$('#start').datepicker({
dateFormat: "yy-mm-dd",
beforeShowDay: function(date) {
var highlight = eventDates[date];
if (highlight) {
return [true, "event", 'Tooltip text'];
} else {
return [true, '', ''];
}
}
});
});
});
</script>
Jquery to fetch all dates
<script>
$(function() {
// An array of dates
var eventDates = {};
<?php
$sql = "SELECT * from `ut_trips` WHERE `deisel` > 0";
$result = $connect->query($sql);
while( $final=$result->fetch_assoc() )
{
?>
eventDates[new Date('<?php
$orgDate = date($final['date']);
$date = str_replace('-"', '/', $orgDate);
$newDate = date("Y/m/d", strtotime($date));
echo $newDate ?>')] = new Date(
'<?php $orgDate =date($final['date']);
$date = str_replace('-"', '/', $orgDate);
$newDate = date("Y/m/d", strtotime($date));
echo $newDate
?>'
);
<?php
}
?>
// datepicker
$('#start').datepicker({
dateFormat: "yy-mm-dd",
beforeShowDay: function(date) {
var highlight = eventDates[date];
if (highlight) {
return [true, "event", 'Tooltip text'];
} else {
return [true, '', ''];
}
}
});
});
});
</script>
ajax PHP file
<?php
include("../partials/connect.php");
$v = $_POST['val'];
$sql = "SELECT * from `table` WHERE `value1` > 0 AND `value2` = '".$v."'";
$result = $connect->query($sql);
while( $final=$result->fetch_assoc() )
{
?>
eventDates[new Date('<?php
$orgDate = date($final['date']);
$date = str_replace('-"', '/', $orgDate);
$newDate = date("Y/m/d", strtotime($date));
echo $newDate ?>')] = new Date(
'<?php $orgDate =date($final['date']);
$date = str_replace('-"', '/', $orgDate);
$newDate = date("Y/m/d", strtotime($date));
echo $newDate
?>'
);
<?php
}
?>
console output
eventDates[new Date('2021/11/10')] = new Date(
'2021/11/10'
);
eventDates[new Date('2021/11/12')] = new Date(
'2021/11/12'
);
eventDates[new Date('2021/11/13')] = new Date(
'2021/11/13'
);
Update:
echo out the date in jason format
echo jason_encode($newDate);
Jquery
dataType: "json",
success: function(data) {
console.log(data);
return data;
}
using dataType: "json" outputs nothing in console and if I comment It out it will output eventDates[new Date('2021\/11\/12')] = new Date( '2021\/11\/12' );
in colsole.