This is the structure of SQL table called "calende_bookings".
TABLE `calende_bookings`
- `id`,
- `id_item`,
- `the_date`,
- `id_state`,
- `id_booking`,
- PRIMARY KEY (`id`)
The goal is to get reservation dates which already existing in database and update Datepicker ui which will disable those date ranges in Datapicker, so users will not be able to pick them when they made reservations. Start date is always afternoon so id_state=3 is always start date (from: in outcome case), and date with last id_state=1 before date with id_state=2 is always last date (to: in outcome case). Two items will be displayed seperetely so I need the thing for one of them. This need to be outcome (dynamic dates).
var disabledArrFromTo = [
{ "from": "21-06-2021", "to": "26-06-2021" },
{ "from": "12-08-2021", "to": "14-08-2021" },
{ "from": .....}
]
This is my Datepicker code who actually work fine but when I wrote disabled date-ranges manualy. I used many example with simple dates, so no dates ranges, it disabled dates in Datapicker, but entire script stop with prices calculation.
$(window).load(function () {
$(document).ready(function() {
// An array of objects containing disabled date ranges
var disabledArrFromTo = [ { "from": "1-08-2021", "to": "19-08-2021" }, { "from": "23-08-2021", "to": "9-09-2021" } ];
$("#fromto").datepicker({
beforeShowDay: function(date){
//console.log(date);
// For each calendar date, check if it is within a disabled range.
for(i=0;i<disabledArrFromTo.length;i++){
// Get each from/to ranges
var From = disabledArrFromTo[i].from.split("-");
var To = disabledArrFromTo[i].to.split("-");
// Format them as dates : Year, Month (zero-based), Date
var FromDate = new Date(From[2],From[1]-1,From[0]);
var ToDate = new Date(To[2],To[1]-1,To[0]);
// Set a flag to be used when found
var found=false;
// Compare date
if(date>=FromDate && date<=ToDate){
found=true;
return [false, "red"]; // Return false (disabled) and the "red" class.
}
}
//At the end of the for loop, if the date wasn't found, return true.
if(!found){
return [true, "blue"]; // Return true (Not disabled) and no class.
}
},
buttonImage: "images/calendar_h.png",
buttonText: "Arrival",
buttonImageOnly: true,
changeMonth: true,
changeYear: true,
dateFormat: "dd-mm-yy",
altField: "#fromto",
altFormat: "dd-mm-yy",
gotoCurrent: true,
maxDate: "+2Y",
showOn: 'both',
yearRange: "-0:+2",
minDate: "+1D",
setDate: "+1",
numberOfMonths: 1,
onSelect: function (startDate, inst) {
var date = startDate.split("-");
$('#dd').val(date[0]);
$('#md').val(date[1]);
$('#yd').val(date[2]);
var date = $(this).datepicker('getDate');
if (date) {
date.setDate(date.getDate() + 3);
}
$("#tofrom").datepicker("option","minDate", date)
var startDate = new Date(parseInt($('#yd').val(),10),parseInt($('#md').val(),10)-1,parseInt($('#dd').val(),10));
$('.dirko').text($.datepicker.formatDate('dd. mm. yy', new Date(startDate)));
$('.ddirko').text($.datepicker.formatDate('D dd MM yy', new Date(startDate)));
}
});
$("#tofrom").datepicker({
beforeShowDay: function(date){
//console.log(date);
// For each calendar date, check if it is within a disabled range.
for(i=0;i<disabledArrFromTo.length;i++){
// Get each from/to ranges
var From = disabledArrFromTo[i].from.split("-");
var To = disabledArrFromTo[i].to.split("-");
// Format them as dates : Year, Month (zero-based), Date
var FromDate = new Date(From[2],From[1]-1,From[0]);
var ToDate = new Date(To[2],To[1]-1,To[0]);
// Set a flag to be used when found
var found=false;
// Compare date
if(date>=FromDate && date<=ToDate){
found=true;
return [false, "red"]; // Return false (disabled) and the "red" class.
}
}
//At the end of the for loop, if the date wasn't found, return true.
if(!found){
return [true, ""]; // Return true (Not disabled) and no class.
}
},
buttonImage: "images/calendar_h.png",
buttonText: "Departure",
buttonImageOnly: true,
changeMonth: true,
changeYear: true,
dateFormat: "dd-mm-yy",
altField: "#tofrom",
altFormat: "dd-mm-yy",
gotoCurrent: true,
maxDate: "+2Y",
showOn: 'both',
yearRange: "-0:+2",
minDate: "+1D",
numberOfMonths: 1,
onSelect: function (endDate, inst) {
var eDates = endDate.split("-");
$('#dr').val(eDates[0]);
$('#mr').val(eDates[1]);
$('#yr').val(eDates[2]);
var endDate = new Date(parseInt($('#yr').val(),10),parseInt($('#mr').val(),10)-1,parseInt($('#dr').val(),10));
$('.cirko').text($.datepicker.formatDate('dd. mm. yy', new Date(endDate)));
$('.ccirko').text($.datepicker.formatDate('D dd MM yy', new Date(endDate)));
}
});
});
I extracted dates from databese table in PHP for future dates with this ...
/*ITEM 1*/
SELECT
id_item,
id_state,
id_date,
DATE_FORMAT (the_date, "%e-%m-%Y") AS from_the_date
FROM calende_bookings
WHERE the_date > now()
AND id_item = 1
AND (id_state = 3 || id_state = 1)
ORDER by the_date ASC
My test PHP file connection with database.
<?php
$servername = "********";
$username = "***********";
$password = "***********";
$dbname = "***********";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo 'var disabledArrFromTo = [';
$sql = 'SELECT
id_item,
id_state,
the_date,
DATE_FORMAT (the_date, "%e-%m-%Y") AS from_the_date
FROM calende_bookings
WHERE the_date > now()
AND id_item = 1
AND (id_state = 3
|| id_state = 1)
ORDER by the_date ASC';
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo '"'. $row['from_the_date'] . '",';
}
} else {
echo "0 results";
}
echo '"31-12-2076"];';
$conn->close();
?>
Outcome look like this:
var disabledArrFromTo = ["25-06-2021","26-06-2021","31-12-2076"];
and I need something like this (startdate = date with item_state = 3 and enddate is last item_state = 1 before item_state = 2, check image on the top of the post):
var disabledArrFromTo = [
{ "from": "21-06-2021", "to": "26-06-2021" },
{ "from": "12-08-2021", "to": "14-08-2021" },
{ "from": .....}
]
Try this: Prepare an array with all disabled dates
var disabledDates =['01/01/2020', '02/02/2020'];
function checkDayAvailable(day) { var fDay=day.getDate() + '/'+ (day.getMonth()+1) + "/" + day.getFullYear(); return inArray(fDay, disabled Dates) }
$('#iDate').datepicker({ beforeShowDay: checkDayAvailable });
Sorry, I'm on my phone, maybe I've made some syntax errors
So, for bringing data from db and update the JS array you can do it two ways:
Insert php code in you page. This code will get data from db and then echo it into JS code; This may look like:
<?php
//.....
//.....
$serverName = "your_server_name";
$connectionString = array( "Database"=>"dbName", "UID"=>"username", "PWD"=>"password");
$conn = sqlsrv_connect( $serverName, $connectionString );
if( $conn === false ) {
die( print_r( sqlsrv_errors(), true));
}
$sql = "SELECT * FROM calendar_bookings";
$res = sqlsrv_query( $conn, $sql );
if( $res === false) {
die( print_r( sqlsrv_errors(), true) );
}
$r="'";
while( $row = sqlsrv_fetch_array( $res, SQLSRV_FETCH_ASSOC) ) {
$r.=$row['the_date']."',";
}
sqlsrv_free_stmt( $res);
$r=substr($r, 0, -1);
?>
<script language="javascript">
var var disabledDates =[<?php=$r ?>];
By using an external service called by an ajax call. In this case you will need an external file which contains all php code. For example (supposing you are using jquery in your page): php file (let's call it server.php) will look like:
<?php
$serverName = "your_server_name";
$connectionString = array( "Database"=>"dbName", "UID"=>"username", "PWD"=>"password");
$conn = sqlsrv_connect( $serverName, $connectionString );
if( $conn === false ) {
die( print_r( sqlsrv_errors(), true));
}
$sql = "SELECT * FROM calendar_bookings";
$res = sqlsrv_query( $conn, $sql );
if( $res === false) {
die( print_r( sqlsrv_errors(), true) );
}
$r=[];
while( $row = sqlsrv_fetch_array( $res, SQLSRV_FETCH_ASSOC) ) {
$r[]=$row['the_date'];
}
sqlsrv_free_stmt( $res);
exit json_encode($r);
?>
your js code (supposing you are using jquery, just for simplyfing):
....
<script>
$.post(
'/server.php',
{},
function(data){
try {
var disabledDates = JSON.parse(data);
//now do whatever you need with
} catch(e){
console.warn(e);
}
}
);
</script>
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Find the answer in similar questions on our website.
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.
PHP (from the English Hypertext Preprocessor - hypertext preprocessor) is a scripting programming language for developing web applications. Supported by most hosting providers, it is one of the most popular tools for creating dynamic websites.
The PHP scripting language has gained wide popularity due to its processing speed, simplicity, cross-platform, functionality and distribution of source codes under its own license.
https://www.php.net/
JavaScript is a multi-paradigm language that supports event-driven, functional, and mandatory (including object-oriented and prototype-based) programming types. Originally JavaScript was only used on the client side. JavaScript is now still used as a server-side programming language. To summarize, we can say that JavaScript is the language of the Internet.
https://www.javascript.com/
JQuery is arguably the most popular JavaScript library with so many features for modern development. JQuery is a fast and concise JavaScript library created by John Resig in 2006. It is a cross-platform JavaScript library designed to simplify client-side HTML scripting. Over 19 million websites are currently using jQuery! Companies like WordPress, Facebook, Google, IBM and many more rely on jQuery to provide a kind of web browsing experience.
https://jquery.com/
DBMS is a database management system. It is designed to change, search, add and delete information in the database. There are many DBMSs designed for similar purposes with different features. One of the most popular is MySQL.
It is a software tool designed to work with relational SQL databases. It is easy to learn even for site owners who are not professional programmers or administrators. MySQL DBMS also allows you to export and import data, which is convenient when moving large amounts of information.
https://www.mysql.com/
Welcome to the Q&A site for web developers. Here you can ask a question about the problem you are facing and get answers from other experts. We have created a user-friendly interface so that you can quickly and free of charge ask a question about a web programming problem. We also invite other experts to join our community and help other members who ask questions. In addition, you can use our search for questions with a solution.
Ask about the real problem you are facing. Describe in detail what you are doing and what you want to achieve.
Our goal is to create a strong community in which everyone will support each other. If you find a question and know the answer to it, help others with your knowledge.