I am trying to retrieve dates from MySQL database which will be used to dynamically disable dates in the datepicker UI. I have retrieved the dates from the database and encoded it in a JSON. This is the output of the echo JSON:
[
{"dates":"21-03-2016"},
{"dates":"31-03-2016"},
{"dates":"31-03-2016"},
{"dates":"30-03-2016"}
]
I have tried to getJSON to the javascript page where it will be retrieved and used to eliminate the dates. However, it is not working as the datepicker UI is not even appearing anymore.
Any suggestions? Thank You.
checkDates.php
<?php
$servername = "localhost";
$username = "user";
$password = "user";
$dbname = "ebooking";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "select booking_date from booking";
$result = $conn->query($sql);
$checkDates = array();
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$checkDate['dates'] = $row['booking_date'];
$checkDates[] = $checkDate;
}
} else {
echo "0 results";
}
echo json_encode($checkDates);
$conn->close();
?>
index.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<link rel="stylesheet"
href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css">
<script>
$(function() {
$( "#datepicker" ).datepicker({
dateFormat: 'dd-mm-yy',
beforeShowDay: checkAvailability
});
})
$.getJSON('checkDates.php?dld='+ id, function(json){dates=json;});
function checkAvailability(mydate){
var myBadDates = dates;
var $return=true;
var $returnclass ="available";
$checkdate = $.datepicker.formatDate('dd-mm-yy', mydate);
// start loop
for(var x in myBadDates)
{
$myBadDates = new Array( myBadDates[x]['start']);
for(var i = 0; i < $myBadDates.length; i++)
if($myBadDates[i] == $checkdate)
{
$return = false;
$returnclass= "unavailable";
}
}
//end loop
return [$return,$returnclass];
}
</script>
</head>
<body>
Date:
<input type="text" id="datepicker">
</body>
</html>
header('Content-Type: application/json');Also, in your checkAvailability javascript function where does the "dates" variable come from? It's not being assigned in $.getJSON line.datesin the $.getJSON line is not global. You should declaredatesoutside of a function in order to use it globally. Near the top of your script tags:var dates;. You should also rename your javascript variables without $ as it is very confusing.