0

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>

8
  • Are you mixing Jquery and php in your index file? Commented Mar 26, 2016 at 15:48
  • @Torchify in my index file, I am both using jquery and php. Commented Mar 26, 2016 at 15:54
  • Your mime type on your checkdates.php must be set to application/json. not sure if you did that since the whole file is not there. try: 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. Commented Mar 26, 2016 at 16:11
  • More specifically, the scope of dates in the $.getJSON line is not global. You should declare dates outside 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. Commented Mar 26, 2016 at 16:31
  • @Torchify I am quite confused in how to implement your suggestion. Are you able to rectify my code? Commented Mar 26, 2016 at 16:37

2 Answers 2

1

ok, so I've altered your javascript a bit, and here's the code I've come up with:

$(function() {
  //ajax call better placed here.
  id="my ID"; //Define id, as it's not defined in the original post.
  /* Commented out just for JsFiddle, uncomment this for live version.
  $.getJSON('checkDates.php?dld=' + id, function(json) {
    dates = json;


    $("#datepicker").datepicker({
      dateFormat: 'dd-mm-yy',
      beforeShowDay: checkAvailability

    });
  });
  */
  //For JsFiddle ONLY remove this section of code for live version.
  dates = [{
    "dates": "21-03-2016"
  }, {
    "dates": "31-03-2016"
  }, {
    "dates": "31-03-2016"
  }, {
    "dates": "30-03-2016"
  }];
  $("#datepicker").datepicker({
    dateFormat: 'dd-mm-yy',
    beforeShowDay: checkAvailability

  });
  //End for JsFiddle
});




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) {

    if (myBadDates[x].dates == $checkdate) {
      $return = false;
      $returnclass = "unavailable";
    }



  } //end loop



  return [$return, $returnclass];
}

Please see jsFiddle: https://jsfiddle.net/gregborbonus/v1dwqq5r/1/

If the ajax fails, then it will break.

I've edited the code and the updated jsFiddle is here: https://jsfiddle.net/gregborbonus/v1dwqq5r/2/

You're php may be spitting out something different, if this doesn't work for you, link to your php script, and I can test for the correct headers and test the ajax call itself, but I doubt that's even an issue.

Sign up to request clarification or add additional context in comments.

10 Comments

With the static variable, it works but when I try to implement the JSON, the datepicker UI doesn't appear when I click the textbox.
@abcdefg If you edited your php for my solution you would need to put it back to your original nested array for Greg's.
@GregBorbonus I just implemented your second version and the datepicker UI does appear but the dates are still available. From what I understand, is there a problem with the transportation of the JSON between the php file and JavaScript file? Does the location of the php file affect this?
That's an issue with the ajax url itself. You should be able to use the inspector to see where the error is coming from.
Yes, the location does affect this. So, lets say index.jsp is in the root of your site: /index.jsp, then you place the checkDates.php file in the same directory, then all your js scripts should point to /checkDates.php (notice the /). Now, if you want it in another folder, then you would do: /folder/checkDates.php for you js, and you would move checkDates.php into the folder called folder.
|
0

checkdates.php

<?php
//Set document mime type... this is important since you want to return json not text!
header('Content-Type: application/json');

$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()) {
        $checkDates[] = $row['booking_date'];
    }
} 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">


</head>
<body>
Date:
<input type="text" id="datepicker">
</body>
<script>
    var badDates;
    $.getJSON('checkDates.php, function(json){badDates=json;});

    $(function() {
        $( "#datepicker" ).datepicker({
            dateFormat: 'dd-mm-yy',
            beforeShowDay: function(date) {
                if($.inArray($.datepicker.formatDate('dd-mm-yy', date ), badDates) > -1)
                {
                    return [false,"Unavailable","Booked"];
                }
                else
                {
                    return [true,"Available","Not Booked"];
                }
            }
        });
    })

</script>
</html>

Try this. I added the content type to the php file. I also changed the javascript around a bit.

Edited for flat array in php file, Thanks @Greg_Borbonus

9 Comments

Nice code, very clean. The only issue is that the php code is this: ` $checkDate['dates'] = $row['booking_date']; $checkDates[] = $checkDate;` This puts the array $checkDate as a new element on the array $checkDates. for your js code to work, you need a single dimensional array, this php code creates a 2 dimensional array.
@Torchify Thank you for the suggestion. I have implemented your suggestion but the unavailable dates are not being greyed out. Where do I place the PHP file in the folder structure? Do I place it in the Web Content folder?
I checked my code in a fork of @GregBorbonus fiddle and it works. (see here: jsfiddle.net/qo74smpz ) Can you inspect the xhm return in chrome devtools and see what the php is returning? Otherwise you can implement Greg's solution.
@Torchify With the static dates, it works exactly the same and how it should do. But when I uncomment the live version and get rid of the static dates, all dates are available on the UI.
@abcdefg Can you test the return of your php file? Please post exactly what is returned. You can check this in chrome devtools or equivalent.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.