Home > database >  Store json values to an array
Store json values to an array

Time:10-23

Hello I have not much experience but usually with some help of google I can figure it out, but not today. I am making an appointment program and I am struggling with blocking values from a DB in the datepicker.

JS:

  <script>
  $( function() {
    $( "#datepicker" ).datepicker({
      minDate: 2,
      maxDate: "1w",
      beforeShowDay: function(date)
      {
          var dates = new Array();
          $.ajax({
              url:"load_days.php",
              type:"POST",
              success:function(data)
              {
                for (var i = 0; i < data.length; i  ){
                  dates.push(data)
                }
              },
              dataType:"json"
            })
            var string = jQuery.datepicker.formatDate('dd-mm-yy', date);
            return [ dates.indexOf(string) == -1 ]
      }
    });
  } );
  </script>

PHP file:

$data = array();

$query = "SELECT * FROM events ORDER BY id";

$statement = $connect->prepare($query);

$statement->execute();

$result = $statement->fetchAll();

foreach($result as $row)
{
    $data[] = array(
        'day'     =>  date("d-m-Y", strtotime($row["start_event"]))
    );
}

echo json_encode($data);

CodePudding user response:

First, I would suggest modifying the PHP script to remove the ['day' => date] array wrapper around the date of each event. That will make it easier for JavaScript to find dates in the array.

foreach($result as $row) {
    $data[] = date("d-m-Y", strtotime($row["start_event"]));
}

Then I would reorganize the JS a bit so that the dates from load_days.php are only loaded once and then reused rather than reloaded in each beforeShowDay event. After reformatting the data that PHP is returning as shown above, the array returned by ajax can be used directly, so the for loop is no longer needed to transform it.

$( function() {
    $.ajax({
        url: "load_days.php",
        type: "POST",
        success: function (dates) {
            $( "#datepicker" ).datepicker({
                minDate: 2,
                maxDate: "1w",
                beforeShowDay: function(date)
                {
                    var string = jQuery.datepicker.formatDate('dd-mm-yy', date);
                    return [dates.indexOf(string) === -1]
                }
            })
        },
        dataType: "json"
    });
})
  • Related