Search code examples
javascriptjqueryajaxjquery-uijquery-ui-datepicker

Use jQuery UI datepicker with async AJAX requests


I am trying to enable specific days in a jquery-ui datepicker. So far i have set my sql scripts and json files and everything is working fine except the response time, because i've set async to false. My jquery code is.

var today = new Date();

$("#pickDate").datepicker({
    minDate: today,
    maxDate: today.getMonth() + 1,
    dateFormat: 'dd-mm-yy',
    beforeShowDay: lessonDates,
    onSelect: function(dateText) {
        var selectedDate = $(this).datepicker('getDate').getDay() - 1;
        $("#modal").show();
        $.get("http://localhost/getTime.php", {
            lessonDay: selectedDate,
            lessonId: $("#lesson").val()
        }, function(data) {
            $("#attend-time").html("");
            for (var i = 0; i < data.length; i++) {
                $("#attend-time").append("<option>" + data[i].lessonTime + "</option>");
                $("#modal").hide();
            }
        }, 'json');
    }
});

function lessonDates(date) {
    var day = date.getDay();
    var dayValues = [];
    $.ajax({
        type: "GET",
        url: "http://localhost/getLessonDay.php",
        data: {
            lessonId: $("#lesson").val()
        },
        dataType: "json",
        async: false,
        success: function(data) {
            for (var i = 0; i < data.length; i++) {
                dayValues.push(parseInt(data[i].lessonDay));
            }
        }
    });
    if ($.inArray(day, dayValues) !== -1) {
        return [true];
    } else {
        return [false];
    }
}

Can anyone help me out? I repeat the above code is working fine but with not good response time due to async=false.

Thanks!


Solution

  • You are doing it all wrong. In your example, a synchronous AJAX request is fired for every day in the month. You need to re-factor your code like this (rough outline):

    // global variable, accessible inside both callbacks
    var dayValues = [];
    
    $("#pickDate").datepicker({
      beforeShowDay: function(date) {
        // check array and return false/true
        return [$.inArray(day, dayValues) >= 0 ? true : false, ""];
      }
    });
    
    // perhaps call the following block whenever #lesson changes
    $.ajax({
      type: "GET",
      url: "http://localhost/getLessonDay.php",
      async: true,
      success: function(data) {
        // first populate the array
        for (var i = 0; i < data.length; i++) {
          dayValues.push(parseInt(data[i].lessonDay));
        }
        // tell the datepicker to draw itself again
        // the beforeShowDay function is called during the processs
        // where it will fetch dates from the updated array
        $("#pickDate").datepicker("refresh");
      }
    });
    

    See similar example here.