Search code examples
jquerydatetimepickerbootstrap-datetimepickereonasdan-datetimepicker

Error with plugin datetimepicker in JQuery with ajax


I try to do this, disable all dates and enable the dates that i pass with parameters

This code not work

$.ajax({
    method: "GET",
    url: "url",
})
.success(function(msg) {
    console.log(JSON.parse(msg));
    var disableIni = JSON.parse(msg);

    var disable = [];

    for (var i = 0; i < disableIni.length; i++)
    {
        disable[i] = moment(disableIni[i][0] + "/" + disableIni[i][1] + "/" + disableIni[i][2], "M/DD/YYYY");
        if (i > 5)
        {
            break;
        }
    }

    console.log(disable);

    var vectorTest = [moment("5/25/2017", "M/DD/YYYY"), moment("5/26/2017", "M/DD/YYYY"), moment("5/27/2017", "M/DD/YYYY")];

    console.log(vectorTest);

    var vector = disable;
    console.log(vector);

    $('#input_from').datetimepicker({
        locale: 'es',
        format: 'DD-MM-YYYY',
        enabledDates: $.each(vector, function(i, value) {
            return value;
        })
    });
});

But if i change var vector = disable for var vector = vectorTest, work correctly:

$.ajax({
    method: "GET",
    url: "url",
})
.success(function(msg) {
    console.log(JSON.parse(msg));
    var disableIni = JSON.parse(msg);

    var disable = [];

    for (var i = 0; i < disableIni.length; i++)
    {
        disable[i] = moment(disableIni[i][0] + "/" + disableIni[i][1] + "/" + disableIni[i][2], "M/DD/YYYY");
        if (i > 5)
        {
            break;
        }
    }

    console.log(disable);

    var vectorTest = [moment("5/25/2017", "M/DD/YYYY"), moment("5/26/2017", "M/DD/YYYY"), moment("5/27/2017", "M/DD/YYYY")];

    console.log(vectorTest);

    var vector = vectorTest;
    console.log(vector);

    $('#input_from').datetimepicker({
        locale: 'es',
        format: 'DD-MM-YYYY',
        enabledDates: $.each(vector, function(i, value) {
            return value;
        })
    });
});

Its possible to do that i want??

EDIT

The ajax response:

enter image description here

It's an array that contains other array with 3 position. [0] => Month, [1] => Day, [2] => Year

Thanks


Solution

  • You can do something like the following:

    $.ajax({
      method: "GET",
      url: "url",
      dataType: "json",
      success: function(response){
        var disable = [];
        for(var i=0; i<response.length; i++){
          var data = response[i];
          disable.push( moment([ data[2], data[0], data[1] ]) );
        }
    
        $('#input_from').datetimepicker({
          locale: 'es',
          format: 'DD-MM-YYYY',
          enabledDates: disable
        });
      }
    });
    

    You can use success and dataType key of jQuery.ajax.

    Then you can loop your results and build an array of moment objects using moment(Array) method and pass it to enabledDates option of the datetimepicker.