Skip to content
Advertisement

How can I retrieve the selected date value from datepicker jQuery UI in order to trigger something

As the title mentions, I want to update my page with data in accordance with selected date in jQuery UI datepicker. So i need to retrieve the current date value if no date is selected or retrieve the selected date data and crush the current date value, so I can dynamically show things on the page regarding the selected date.

Here is my code for the datepicker so far :

var date_choisie;

$( function() {
    $("#calendrier").datepicker({
        dateFormat: "yy-mm-dd",
        onSelect: function(selectedDate) {
        // console.log(selectedDate); //Selected date
        date_choisie = selectedDate; //My attempt to put selectedDate in date_choisie
        }
    })
    //set date as current by default
    $("#calendrier").datepicker('setDate', new Date());

    //get date in a variable
    date_choisie = $('#calendrier').datepicker('getDate');
    date_choisie = $.datepicker.formatDate("yy-mm-dd", date_choisie);

    // console.log(date_choisie); //2020-09-20
} );

So I need to be able to get selectedDate in date_choisie (maybe I should return selectedDate)

After this I will pass date_choisie to my PHP file by using ajax :

$.ajax({
    method: 'get',
    url : 'http://planning-ilm.atwebpages.com/userPlanning/'+ date_choisie,
    dataType : 'json',
    success: function(data){
        let semaine = document.createTextNode('Sem du ' + data.datecourante.mday + '/' + data.datecourante.mon + '/' + data.datecourante.year);
        $("#sem")[0].appendChild(semaine);
        showplannings(data.datecourante, data.message);
    }
})

The URL will call the following php function :

 function getUserPlanning($url){
        // Function used to get the user planning
        $today = getdate(); // This is the line i will change with the selected date

        // Searching for monday, if the selected date is not monday
        if($today ['weekday'] !== "Monday"){
            $monday = getdate(strtotime("last Monday")); //This is the line i will change with the selected date
            
            // We get everything in an array
            $dayMonthYear = dayMonthYearOfDate($monday);

            // Concatenation in string
            $dayMonthYearString = $dayMonthYear['day']. ' ' . $dayMonthYear['month']. ' ' . $dayMonthYear['year'];
        
            // We get every day of the week in array
            $theWeek = currentWeek($dayMonthYearString);

            return $error = json_encode([
                'status' => 'ok',
                'datecourante' => $monday, // Here is the monday of the selected day
                'message' => getHisPlanning($url[1], $theWeek)
            ]);
        }else{
            $dayMonthYear = dayMonthYearOfDate($today);
            $dayMonthYearString = $dayMonthYear['day']. ' ' . $dayMonthYear['month']. ' ' . $dayMonthYear['year'];
            // On a la semaine actuelle
            $theWeek = currentWeek($dayMonthYearString);

            
            return $error = json_encode([
                'status' => 'ok',
                'datecourante' => $today, // Here is the monday of the selected day
                'message' => getHisPlanning($url[1], $theWeek)
            ]);
        }
    }

Here are the functions used in getUserPlanning

function dayMonthYearOfDate($dateTostring){
        // Fonction permettant de retourner le jour, le mois et l'année sous forme de tableau
        $jour = $dateTostring['mday'];
        $mois = $dateTostring['month'];
        $annee = $dateTostring['year'];

        $dateofDay = ['day' => $jour, 'month' => $mois, 'year' => $annee];
        
        return $dateofDay;
    }
function currentWeek($currentDate){
        // Fonction permettant de retourner tous les jours de la semaine courante en prenant un string
        $monday = strtotime($currentDate);
        $tuesday = strtotime("next Tuesday", strtotime($currentDate));
        $wednesday = strtotime("next Wednesday", strtotime($currentDate));
        $thursday = strtotime("next Thursday", strtotime($currentDate));
        $friday = strtotime("next Friday", strtotime($currentDate));
        $saturday = strtotime("next Saturday", strtotime($currentDate));
        $sunday = strtotime("next Sunday", strtotime($currentDate));

        $week = [$monday, $tuesday, $wednesday, $thursday, $friday, $saturday, $sunday];
        return $week;
    }

By using getUserPlanning i can retrieve the selected date which is registered in data.datecourante

Advertisement

Answer

You can wrap your ajax call in a function and then call that function each time you select a new date.

To show the current OR selected date on screen you can use .text function display the date. As soon as the date page is loaded the ajax will be called and the current date data will fetch from PHP.

Lastly, once you do the ajax call you can show the PHP ajax data accordingly in your success function.

Edit: You can pass your selecteddate to this function as well => showplannings(data.datecourante, data.message, selectedDate); add a third argument in this function and receive this third argument in your showplannings function and do whatever is necessary.

Live Demo:

$(function() {
  $("#calendrier").datepicker({
    dateFormat: "yy-mm-dd",
    onSelect: function(selectedDate) {
      //show selected on screen
      $('.selectedDate').text('Selected Date: ' + selectedDate)

      //call ajax on selected date
      myAjaxCall(selectedDate)
    }
  })
  //set date as current by default
  $("#calendrier").datepicker('setDate', new Date());

  //get date in a variable
  let currentDate = $('#calendrier').datepicker('getDate');
  let currentDateFormat = $.datepicker.formatDate("yy-mm-dd", currentDate);

  //Show date on screen
  $('.selectedDate').text('Selected Date: ' + currentDateFormat)

  //Call ajax on load
  myAjaxCall(currentDateFormat) //pass current date to ajax function
});

//Ajax call
function myAjaxCall(selectedDate) {
  $.ajax({
    method: 'get',
    url: 'http://planning-ilm.atwebpages.com/userPlanning/' + selectedDate,
    dataType: 'json',
    success: function(data) {
      //let semaine = document.createTextNode('Sem du ' + data.datecourante.mday + '/' + data.datecourante.mon + '/' + data.datecourante.year);
      //$("#sem")[0].appendChild(semaine);
      //showplannings(data.datecourante, data.message, selectedDate);
                                                 //....^ - pass selected
    }
  })
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">

<p>Date: <input type="text" id="calendrier"></p>

<p class="selectedDate"></p>

<button class="callAjax">Click Ajax</button>
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement