user3125546
user3125546

Reputation: 21

Javascript Array from PHP

To update a Javascript Array (eventDates) I want to get the content via Ajax/PHP – sadly I don’t get it to work. Anyone knows how the PHP output (data) hast to look, that I can work with it?

      $.ajax({
        type: "GET",
        url: "_ajax_registration.php?type=getDate&project="+val,
        data: "data",
        success: function(data){
            var eventDates = data;
        }
      });

      /*
      var eventDates = [{date: new Date(2014, 1-1, 28)}},
                {date: new Date(2014, 1-1, 18)},
                {date: new Date(2014, 6-1, 18)},];
      */


      function showEventDates(date) {
        for (var i = 0; i < eventDates.length; i++) {
            if (date.getTime() == eventDates[i].date.getTime()) {
                return [true, ''];
            }
        }
        return [false, ''];
      }

      $("#datepicker").datepicker("destroy");       
      $( "#datepicker" ).datepicker({       
        beforeShowDay: showEventDates

      }); 
      $( "#datepicker" ).datepicker( "refresh" );   

Upvotes: 0

Views: 71

Answers (3)

Bill Criswell
Bill Criswell

Reputation: 32921

You need to echo json_encode($someArray) from _ajax_registration.php.

Also, you won't be able to access eventDates outside of your ajax callback. You'll need to do:

function showEventDates(date) {
  for (var i = 0; i < eventDates.length; i++) {
    if (date.getTime() == eventDates[i].date.getTime()) {
      return [true, ''];
    }
  }
  return [false, ''];
}

$.ajax({
  type: "GET",
  url: "_ajax_registration.php?type=getDate&project="+val,
  success: function(data){
    var eventDates = data;
    $("#datepicker").datepicker("destroy");       
    $( "#datepicker" ).datepicker({       
      beforeShowDay: showEventDates
    }); 
    $( "#datepicker" ).datepicker( "refresh" );
  }
});

Upvotes: 0

Frank Conry
Frank Conry

Reputation: 2716

What I like to to is, on the php side, take your array and

echo json_encode($myArray));

then, in the jquery you canjust:

$.GetJson('ajax_reg.php', { type : 'getDate', project': val }, function(data) {
    eventDates = date;
});

Upvotes: 0

Max
Max

Reputation: 1478

You have an excrescent bracket after the first and an redundant comma on the last object. Try this:

 var eventDates = [{date: new Date(2014, 1-1, 28)},
            {date: new Date(2014, 1-1, 18)},
            {date: new Date(2014, 6-1, 18)}];

Upvotes: 1

Related Questions