Adding background to days with event with FullCalendar - javascript

I've defined a function to check whether a date has an event that returns true or false. For some reason, it's turning the cell of the next day to the color instead of the day that has an event. Oddly enough, my partner is using linux and it displays correctly for him, but every computer or vm i try it on with any operating system displays incorrectly. Here is the relevant code and a jsfiddle that displays the problem:
$(document).ready(function() {
var events = [];
$.ajax({
url : 'https://showmeyouraxels.me/browse.php',
type : 'post',
dataType: 'json',
success: function(e){
console.log(e[0].title);
for(var i = 0; i < e.length; i++){
events.push({
title : e[i].title,
start : moment(e[i].start).toDate('2017/07/18 12h:00'),
end : moment(e[i].end).toDate('2017/07/18 12h:30'),
icon: "https://www.qrstuff.com/images/sample.png",
});
}
console.log(events);
createCalendar();
}
});
function createCalendar(){
var calendar = $('#calendar').fullCalendar({
customButtons: {
myCustomButton: {
text: 'Add Event',
click: function() {
alert('add event');
}
}
},
header: {
left: 'prev',
center: 'title',
right: 'next'
},
editable : false,
eventLimit: true,
eventLimitText: '',
dayRender: function (date, cell) {
if ( !dateHasEvent(date) ){
cell.css("background-color", "initial");
console.log('no event ' + date.toDate());
}
else if ( dateHasEvent(date) ){
cell.css("background-color", "#6b7c8c");
console.log('event ' + date.toDate());
}
},
eventClick: function(calEvent, jsEvent, view, element) {
var inner = new Date(calEvent.start) + ' to ' + new Date(calEvent.end);
swal({
title: calEvent.title,
html: true,
text: inner,
allowOutsideClick: true
});
},
dayClick: function(dayEvent, jsEvent, view, element){
console.log(dayEvent);
},
eventRender: function(event, element) {
element.find('.fc-content').html('<img src="http://simpleicon.com/wp-content/uploads/flag.svg" height="10px"/><br>' +event.title);
},
});
calendar.fullCalendar( 'addEventSource', events);
}
function dateHasEvent(date) {
var hasEvent = false;
for(var i = 0; i < events.length; i++){
var thatDate = events[i].start.toString();
thatDate = thatDate.split(' ');
thatDate = thatDate[1] +' '+thatDate[2] +' '+thatDate[3];
var thisDate = date.toDate().toString();
thisDate = thisDate.split(' ');
thisDate = thisDate[1] +' '+thisDate[2] +' '+thisDate[3];
if(thisDate == thatDate){
hasEvent = true;
}
}
return hasEvent;
}
});
JSFiddle
I've been scratching my head for the past day and i'd have to imagine it's something stupid that i'm missing.
Thank you for any help you can provide!

Related

How do I speed up Javascript event handlers?

I implemented a list of courses so that when a course name is hovered over, the corresponding dates on the calendar are highlighted.
Javascript parses the dates when it is loaded and stores it with the DOM element, so that on mouseenter and mouseleave, JQuery highlights or removes the highlighting of the corresponding table cells in the calendar.
However, the page takes 8 seconds for the list of courses and the calendar to load and another 1 second to highlight or remove the highlighting of the table cells. coursesLoaded is when the course list finishes loading.
(function($) {
$(window).load(function() {
if ($('.calendar').length) {
var calendarOs = [];
$('.calendar').each(function(i, v){
$(this).html('');
$(this).prev().hide();
var calendar = $(this);
calendar.attr('index', i);
calendarO = new FullCalendar.Calendar(calendar[0], {
plugins: [ 'dayGrid' ],
defaultView: 'dayGridMonth',
header: {
left: '',
center: 'title',
right: ''
},
titleFormat: {
year: 'numeric',
month: 'long'
},
themeSystem: 'bootstrap',
fixedWeekCount: true,
contentHeight: "auto",
navLinks: false,
eventRender: function(event, eventElement) {
eventElement.addClass('calendar');
},
validRange: function(currentDate) {
return {
start: new Date(currentDate.getFullYear(), currentDate.getMonth(), 1),
// end: new Date(currentDate.getFullYear(), currentDate.getMonth() + 4, 0)
};
}
});
calendarO.render();
calendarOs.push(calendarO);
});
var year = new Date().getFullYear();
var date, location, color, array, td;
//make update only one color
var updateColors = function(index) {
var calendar = $(`.calendar[index='${index}']`);
var calendarO = calendarOs[index];
var month = calendarO.getDate().getMonth();
var datesO = JSON.parse(calendar.attr('dates'));
calendar.find('td.richmond, td.burnaby').removeClass('richmond burnaby');
var traverseDates = (month == 0) ? [11, 0, 1] : ((month == 11) ? [10, 11, 0] : [month - 1, month, month + 1]);
traverseDates.forEach(function(month) {
datesO[month].forEach(function(obj) {
// console.log(obj)
calendar.find(`td[data-date=${obj.date}]:not(.fc-day-top)`).addClass(obj.location);
});
});
}
$(document).on(`coursesLoaded`, function(e, calendarIndex, dates) {
// console.log('coursesLoaded ' + calendarIndex);
var calendar = $(`.calendar[index='${calendarIndex}']`);
var calendarO = calendarOs[calendarIndex];
calendar.attr('dates', JSON.stringify(dates));
console.log(calendar.attr('dates'));
updateColors(calendarIndex);
calendar.parent().prev().find('ul.courses-list li a').hover(function(e){
console.log("hovering over: " + performance.now());
calendar.find('td.active').removeClass('active');
location = $(this).attr('location');
array = JSON.parse($(this).attr('dates'));
calendarO.gotoDate(array[0]);
updateColors(calendarIndex);
if (e.type == 'mouseenter') {
array.forEach(function(element) {
calendar.find(`td[data-date=${element}]:not(.fc-day-top)`).addClass('active');
});
}
console.log("done hovering: " + performance.now());
});
});
};
$(document).trigger('doneCalendars');
});
})(jQuery)
Here is the website: http://ess.ccmcanada.org/certified-training/

How to disable dates between the saved events in fullcalendar

I am using a fullcalendar for creating schedules. What I am doing is, for each week, there must be only 3 schedules (processing date, payout date and credit date). If there are already schedules for that week, I need to prompt the user that schedules are already set. But if there's no schedule set, user can still post new schedule. I am already done with the logic of this scheduler, the only problem I have is how to disable dates between the set schedules for the week?
Example, I set 04-24-2018(processing date), 04-24-18(payout date) and 04-26-18(credit date)..
How can I disable the 04-22-18,04-23-18,04-25-18,04-27-18 and 04-28-18 on that week so that user cant create new schedules for that week?
schedule image
JAVASCRIPT
select:
function (start, end, jsEvent, view, resource) {
IsDateHasEvent(start);
}
function IsDateHasEvent(date) {
var allEvents = [];
allEvents = $('#calendar').fullCalendar('clientEvents');
var event = $.grep(allEvents, function (v) {
//alert(v.start);
//return +v.start == +date;
if (v.start <= date) {
$("#eventIsAlreadySetModal").modal();
//alert(v.start);
}
});
return event.length > 0;
}
I can get all the dates with events whenever I try to alert the value of start date. But the dates between are still not disabled.
Can someone help me through this?
Thank you so much.
Full Javascript code
$(document).ready(function () {
var events = [];
var selectedEvent = null;
FetchEventAndRenderCalendar();
// ******************************************
// GET ALL SCHEDULES AND DISPLAY IN CALENDAR
// ******************************************
function FetchEventAndRenderCalendar() {
$.ajax({
type: 'GET',
url: '#Url.Action("GetSchedule")',
success: function (data) {
$.each(data, function (i, v) {
var eColor = "";
if (v.status == 'Completed')
{
eColor = '#3498DB';
}
if (v.status == 'Active') {
eColor = '#2CB05B';
}
if (v.status == 'Pending') {
eColor: '#DE6209';
}
events.push({
eventID: v.scheduleId,
title: v.processedDescription,
start: moment(v.processedDatetimeStart),
status: v.status,
color: eColor
});
events.push({
eventID: v.scheduleId,
title: v.payoutDescription,
start: moment(v.payoutDatetimeStart),
status: v.status,
color: eColor
});
events.push({
eventID: v.scheduleId,
title: v.creditDescription,
start: moment(v.creditDatetimeStart),
status: v.status,
color: eColor,
end: moment(v.creditDatetimeStart)
});
})
GenerateCalendar(events);
},
error: function (error) {
alert('failed');
}
})
}
// ******************************************
// GENERATE THE CALENDAR VIEW AND SCHEDULES
// ******************************************
function GenerateCalendar(events) {
$('#calendar').fullCalendar('destroy');
$('#calendar').fullCalendar({
contentHeight: 500,
header: {
left: 'prev,next today',
center: 'title',
right: 'month, agendaWeek, agendaDay, listWeek'
},
navLinks: true,
editable: true,
eventLimit: true,
eventColor: '#2CB05B',
droppable: false,
timeFormat: 'h(:mm)A',
timeZone: 'local',
events: events,
// **************************************
// display the saved schedule in calendar
// **************************************
eventClick:
function (calEvent, jsEvent, view) {
$("#statusLabel").text(calEvent.status);
$("#schedId").val(calEvent.eventID);
$("#schedDesc").html(calEvent.title);
$("#txtDateStart_Edit").val(calEvent.start.format("MM-DD-YYYY HH:mm A"));
$('#modalEditSchedule').modal();
if ($("#statusLabel").html() == "Completed")
{
$("#btnEditSched").hide();
}
if ($("#statusLabel").html() == "Active") {
$("#btnEditSched").hide();
}
},
// *************************************************
// select dates in calendar for posting new schedule
// *************************************************
selectable: true,
selectOverlap: true,
select:
function (start, end, jsEvent, view, resource) {
IsDateHasEvent(start);
},
// *********************************************
// disable past navigation button for past dates
// *********************************************
viewRender: function (currentView) {
var minDate = moment();
// Past dates
if (minDate >= currentView.start) {
$(".fc-prev-button").prop('disabled', true);
$(".fc-prev-button").addClass('fc-state-disabled');
}
else {
$(".fc-prev-button").removeClass('fc-state-disabled');
$(".fc-prev-button").prop('disabled', false);
}
},
// ******************************
// disable past dates in calendar
// ******************************
validRange: function (dateNow) {
return {
start: dateNow.subtract(1, 'days')
};
}
, dayClick: function (date) {
var events = $('#calendar').fullCalendar('clientEvents');
for (var i = 0; i < events.length; i++) {
//if (moment(date).isSame(moment(events[i].start))) {
if (moment(events[i].start) <= moment(date)) {
alert('with events');
break;
}
else //if (i == events.length - 1)
{
alert('none');
}
}
}
});
}
// **********************************
// show modal for adding new schedule
// **********************************
function openAddEditForm() {
$('#modalAddSchedule').modal();
}
});
function IsDateHasEvent(date) {
var allEvents = [];
allEvents = $('#calendar').fullCalendar('clientEvents');
var event = $.grep(allEvents, function (v) {
//alert(v.start);
//return +v.start == +date;
if (v.start <= date) {
$("#eventIsAlreadySetModal").modal();
//alert(v.start);
}
});
return event.length > 0;
}
You need to:
check if there's at least 3 schedules on the same week;
if is there, then disable the other dates of that week.
Right? I'll try to solve the first part of your problem with javascript Date class. I don't know about FullCalendar, so if anyone can solve that part I would be glad, hehe.
We must check when a week starts and when it ends. Just with that we'll get ready to do some crazy stuff.
function printDate(year, month, day) {
month = (month < 10 ? '0' : '') + month.toString();
day = (day < 10 ? '0' : '') + day.toString();
return year + '-' + month + '-' + day;
}
function weekStart(dateString) {
var dateObject = new Date(dateString);
var dayOfWeek = dateObject.getDay();
if(dayOfWeek > 0) {
dateObject.setDate(day - dayOfWeek);
}
return printDate(dateObject.getFullYear(), dateObject.getMonth()+1, dateObject.getDate());
}
function weekEnd(dateString) {
var dateObject = new Date(dateString);
var dayOfWeek = dateObject.getDay();
if(dayOfWeek < 6) {
dateObject.setDate(day + (6-dayOfWeek));
}
return printDate(dateObject.getFullYear(), dateObject.getMonth()+1, dateObject.getDate());
}
function weekRange(dateString) {
return [weekStart(dateString), weekEnd(dateString)];
}
Nice, now we can get a "week range" from a date. But from that, can we get all dates of that week? Sure.
function getDatesFromWeek(wStart) {
var dates = [],
date = new Date(wStart),
count = 0;
while(count <= 6) {
date.setDate(date.getDate() + count);
dates.push(printDate(date.getFullYear(), date.getMonth()+1, date.getDate());
count++;
}
return dates;
}
Perfect. So now we should count for each range. Assuming you're receiving your info on a variable called schedules and each schedule have an index called date:
var weeks = {}, lockedDates = [];
for(var x in schedules) {
var week = weekRange(schedules[x].date);
var weekID = week.join('-');
if(weeks[weekID] == undefined) {
weeks[weekID] = 1;
} else {
weeks[weekID]++;
}
if(weeks[weekID] == 3) {
lockedDates = lockedDates.concat(getDatesFromWeek(week[0]));
}
}
Then you have all those dates to disable listed on lockedDates variable in format YYYY-MM-DD. Do you know how to do the rest?
EDIT
Let's change the last part I made to this:
function Locker() {
this.dates = [];
this.weeks = {};
}
Locker.prototype.add = function(dateString) {
var wStart = weekStart(dateString);
if(this.weeks[wStart] == undefined) {
this.weeks[wStart] = 1;
} else {
this.weeks[wStart]++;
}
if(this.weeks[wStart] == 3) {
this.lock(getDatesFromWeek(wStart));
}
}
Locker.prototype.lock = function(dates) {
this.lockedDates = this.lockedDates.concat(dates);
// do something
}
var calendarLocker = new Locker();
// everytime an user add a date, call calendarLocker.add(date);
// so when it reaches the limit, the locker will call calendarLocker.lock

Full calendar updateEvent. Cannot read property 'clone' of undefined

I'm using FullCalendar and trying to update an event with a modal. When I try to update the event, I'm getting the cannot read property 'clone' of undefined.
I'm using the clientEvents method, as stated in their documentation
event must be the original Event Object for an event, not merely a reconstructed object. The original Event Object can obtained by callbacks such as eventClick, or by the clientEvents method.
to get my original event, however, when I submit I still get this error.
Here's my code:
initializeFullCalendar: function () {
var loc = $('#locationCodes').val();
$('.autocomplete').keypress(function (key) {
if (key.charCode == 32 && $('.autocomplete').val().length >= 1) { return true };
// if (key.charCode == 92 || key.charCode == 47 || key.charCode < 65) return false;
});
$(document).tooltip({
track: true,
hide: { effect: "explode", duration: 300 }
});
$('#calendar').fullCalendar({
header: {
left: 'prev,next today',
center: 'title',
right: 'month,basicWeek,basicDay'
},
selectable: true,
selectHelper: true,
dayclick: function(date){
},
select: function (date, start, end) {
if ($('#job').attr('class') === 'XXX') {
EMP.calendarPopup(date, start, end);
}
},
eventSources: [
{
url: '/Home/getAllEvents/',
data: { Locations: loc },
type: 'POST'
}
],
eventClick: function (event, element, date) {
EMP.editCalendarPopup(date, event);
},
height: 350,
defaultView: 'basicWeek',
editable: true,
eventLimit: true, // allow "more" link when too many events
eventRender: function (data, element) {
var start = moment(data.start._i).format('LT');
var end = moment(data.end._i).format('LT');
}
});
},
editCalendarPopup: function (date, event) {
$('.calendar-popup').addClass('active edit');
var event_date = event.start._i.split("T")[0];
var start = event.start._i.split("T")[1]
var end = event.end._i.split("T")[1];
start = EMP.convert12hr(start);
end = EMP.convert12hr(end);
var startTime = start.split(' ')[0];
var startMod = start.split(' ')[1];
var endTime = end.split(' ')[0];
var endMod = end.split(' ')[1];
$('#date').val(event_date);
$('#calendar-event').val(event.title);
$('#calendar-custodian').val(event.cust);
$('#calendar-start').val(startTime);
$('#startampm').val(startMod)
$('#calendar-end').val(endTime);
$('#endampm').val(endMod);
$('#hiddenEvent').val(event.title);
$('#hiddenCustodian').val(event.cust);
$('#hiddenStart').val(event.start._i);
$('#hiddenEnd').val(event.end._i);
$('#hiddenId').val(event._id);
},
editCalendarAjax: function() {
var event = $("#calendar").fullCalendar('clientEvents');
var hiddenId = $('#hiddenId').val();
event = $.grep(event, function(e){return e._id === hiddenId});
event = event[0];
var event_date = $('#date').val();
var title = $('#calendar-event').val();
var cust = $('#calendar-custodian').val();
var start = $('#calendar-start option:selected').val();
var end = $('#calendar-end option:selected').val();
var startampm = $("#startampm option:selected").val();
var endampm = $("#endampm option:selected").val();
start = start + " " + startampm;
end = end + " " + endampm;
start = EMP.convert24hr(start);
end = EMP.convert24hr(end);
var locCode = $('.location').attr('id');
var date_start = event_date + "T" + start;
var date_end = event_date + "T" + end;
if (title) {
event = {
title: title,
start: date_start,
cust: cust,
end: date_end
};
$('#calendar').fullCalendar('updateEvent', event);
}
var origEvent = $('#hiddenEvent').val();
var origCust = $('#hiddenCustodian').val();
var origStart = $('#hiddenStart').val();
var origEnd = $('#hiddenEnd').val();
item = {};
item["title"] = title;
item["cust"] = cust;
item["start"] = date_start;
item["end"] = date_end;
item["locCode"] = locCode;
item["origEvent"] = origEvent;
item["origCust"] = origCust;
item["origStart"] = origStart;
item["origEnd"] = origEnd;
$.ajax({
type: "POST",
url: "/Home/updateCalendar",
data: item,
success: function () {
console.log('success!');
},
error: function (xhr, ajaxOptions, thrownError) {
window.alert("Please click here to refresh your session");
console.log('error')
}
});
$('#calendar').fullCalendar('unselect');
EMP.togglePopups();
},
The issue was I was using an old version of FullCalendar. After updating I stopped getting the error.
One more thing I had to change was this:
if (title) {
event = {
title: title,
start: date_start,
cust: cust,
end: date_end
};
$('#calendar').fullCalendar('updateEvent', event);
}
to this:
if (title) {
event.title = title;
event.start = date_start;
event.cust = cust;
event.end = date_end;
$('#calendar').fullCalendar('updateEvent', event); // stick? = true
}
because I was overwriting my event. Everything works now.

eventRender not rendering nor displaying events on fullcalendar

Good day, i'm using fullcalendar plugin to show events on my calendar. right now i'm having a problem on displaying the events in my calendar. i am using json result to get the data that will show on my calendar..
here's my code
Controller:
[DontWrapResult]
public JsonResult GetCalendarEvents(string start, string end)
{
var fromDate = Convert.ToDateTime(start);
var toDate = Convert.ToDateTime(end);
var result = _utils.GetEventsCalendar("ALL", fromDate, toDate);
var eventList = from item in result
select new
{
id = item.CalendarId.ToString(),
title = item.Title,
description = item.Description,
start = item.FromDate.ToLocalTime().ToString("s"),
end = item.EndDate.HasValue ? item.EndDate.Value.ToLocalTime().ToString("s") : item.FromDate.ToLocalTime().ToString("s"),
NoofGuests = item.NoofGuests,
allDay = item.AllDay,
type = item.CalType,
requestedBy = item.RequestedBy,
driverName = item.DriverName,
providerName = item.ProviderName,
phoneNo = item.PhoneNo,
controlNumber = item.ControlNumber,
status =item.StatusId
};
var rows = eventList.ToArray();
return Json(rows, JsonRequestBehavior.AllowGet);
}
then in my javascript:
var date = new Date();
var d = date.getDate();
var m = date.getMonth();
var y = date.getFullYear();
$('#calendar').fullCalendar({
header: {
left: 'prev,next today',
center: 'title',
right: 'month,agendaWeek,agendaDay'
},
droppable: false, // this allows things to be dropped onto the calendar
events: '#Url.Action("GetCalendarEvents/")',
eventRender: function (event, element) {
element.attr('href', 'javascript:void(0);');
if (event.start <date && event.end <date) {
element.css('background-color', '#ed5565');
element.css('border', '1px solid #ed5565');
} else if (event.start <=date && event.end >= date) {
element.css('background-color', '#f8ac59');
element.css('border', '1px solid #f8ac59');
}
if (event.status == 1) {
element.css('background-color', '#0000FF');
element.css('border', '1px solid #0000FF');
} else if (event.status == 4)
{
element.css('background-color', '#00CC33');
element.css('border', '1px solid #00CC33');
}
element.click(function () {
if (event.type == 'Event') {
$('#forBook').hide();
$('#permitdetails').hide();
$('#delPer').show();
var url = '#Url.Action("Edit", "Events")?id=' + event.id;
}
else if (event.type == 'ApproveBook') {
$('#forBook').show();
$('#permitdetails').hide();
$('#delPer').show();
$("#NoofGuests").html(event.NoofGuests);
}
else {
$('#forBook').hide();
$('#permitdetails').hide();
$('#delPer').show();
var url = '#Url.Action("Edit", "Announcements")?id=' + event.id;
}
if (event.type == 'DeliveryPermit') {
$('#delPer').hide();
$('#permitdetails').show();
$("#controlNo").html(event.controlNumber);
$("#requestby").html(event.requestedBy);
$("#deliverydate").html(moment(event.start).format('MMM Do'));
$("#contractor").html(event.providerName);
$("#contact").html(event.phoneNo);
$("#drivername").html(event.driverName);
if (event.status == 1) { $("#status").html("Arrived"); }
else if (event.status == 4) { $("#status").html("Completed"); }
else { $("#status").html("Submitted"); }
//getDetails(event.id);
var urls = '#Url.Action("Calendarpermit", "AdminHome")?id=' + event.id + '&strHide=' + "strHide";
var url = '#Url.Action("Edit", "DeliveryPermits",new { area = "Permit" })/' + event.id
$.ajax({
url: urls,
cache: false,
data: {id : event.id},
contentType: 'application/html; charset=utf-8',
type: "POST",
dataType: "html",
success: function (data){
$('#permitItem').html(data);
}
});
}
if (event.type == 'Announcement') {
$('#forBook').hide();
$('#permitdetails').hide();
$('#delPer').show();
$("#startTime").html(moment(event.start).format('MMM Do '));
$("#endTime").html(moment(event.start).format('MMM Do'));
} else {
$("#startTime").html(moment(event.start).format('MMM Do h:mm A'));
$("#endTime").html(moment(event.end).format('MMM Do h:mm A'));
}
$("#eventInfo").html(event.description);
$("#eventLink").attr('href', url);
$("#eventContent").dialog({
modal: true, title: event.title, width: 350
});
});
}
});
i tried to put an alert inside the eventRender but it didn't pass or show data in my calendar.. what i am doing wrong? thanks in advance

JavaScript function array return undefined

I am using AJAX to get the data and make them into an array like below:
function drawDate(username, date, device, token){
$.ajax({
type: 'GET',
url: dsu + "dataPoints/" + getDatapointId(username, date, device),
headers: {
"Authorization": "Bearer " + token
},
success : function(data, device) {
var location_events = []; //***** Here is the array variable.
if(device == "android" || device == "ios") {
rows = data["body"]["episodes"].map(function (epi) {
var state = epi["inferred-state"].toLocaleUpperCase();
var start = new Date(epi["start"]);
var end = new Date(epi["end"]);
var long_lat = epi["location-samples"];
if (state == "STILL") {
var longitude_sum = 0;
var latitude_sum = 0;
long_lat.forEach(function(obj) {
longitude_sum += obj['longitude'];
latitude_sum += obj['latitude'];
});
return [state, start, end, latitude_sum / long_lat.length, longitude_sum / long_lat.length];
}
});
//**** I pushed the data into the array.
rows.forEach(function(obj){
if (typeof obj !== 'undefined') {
location_events.push({
title: 'location',
start: moment(obj[1]).format().substring(0, 19),
end: moment(obj[2]).format().substring(0, 19),
url: "https://maps.googleapis.com/maps/api/staticmap?center="+ obj[3] + "," + obj[4] + "&zoom=15&size=2000x1000&maptype=roadmap&markers=color:red%7Clabel:S%7C" + obj[3] + "," + obj[4] + "&markers=size:mid"
})
}
});
console.log(location_events);
return location_events
}
},
error: function(data){
console.log('Data did not have any locations.')
}
});
}
Then when I tried to call that function, it returned "undefined". I actually want to put that array into FullCalendar like below:
$(document).ready(function() {
var today = moment();
var token = url("#access_token");
$.getJSON(dsu + "oauth/check_token?token=" + token)
.done(function(data) {
var username = data["user_name"];
var device = 'android';
var date = url("#date")? moment(url("#date")).toDate() : new Date();
var redraw = function(){
var test = drawDate(username, moment(date).format('YYYY-MM-DD'), device, token);
console.log(test); //***** Here! I tried to make the return of the function into a variable but it returned "undefined"
};
$('#calendar').fullCalendar({
header: '',
defaultDate: '2015-08-03',
defaultView: 'agendaDay',
allDaySlot: false,
slotEventOverlap: false,
events: test, //******* I want to the array to be rendered here.
eventAfterRender: function(event, element, view) {
$(element).attr("id", "event_id_" + event.id);
}
});
})
.fail(function() {
console.log("Fail!");
});
I read most of the similar questions and it seems that I should use callback function but I don't really understand how to use them.
Thank you very much! Any help is welcome!
The problem is that you do AJAX request which is asynchronous and you cannot return this data from drawDate() function. You need to do what you need with data retrieved from server in your 'success' callback. Like following:
success : function(data, device) {
var location_events = []; //***** Here is the array variable.
if(device == "android" || device == "ios") {
rows = data["body"]["episodes"].map(function (epi) {
var state = epi["inferred-state"].toLocaleUpperCase();
var start = new Date(epi["start"]);
var end = new Date(epi["end"]);
var long_lat = epi["location-samples"];
if (state == "STILL") {
var longitude_sum = 0;
var latitude_sum = 0;
long_lat.forEach(function(obj) {
longitude_sum += obj['longitude'];
latitude_sum += obj['latitude'];
});
location_events = [state, start, end, latitude_sum / long_lat.length, longitude_sum / long_lat.length];
}
});
//**** I pushed the data into the array.
rows.forEach(function(obj){
if (typeof obj !== 'undefined') {
location_events.push({
title: 'location',
start: moment(obj[1]).format().substring(0, 19),
end: moment(obj[2]).format().substring(0, 19),
url: "https://maps.googleapis.com/maps/api/staticmap?center="+ obj[3] + "," + obj[4] + "&zoom=15&size=2000x1000&maptype=roadmap&markers=color:red%7Clabel:S%7C" + obj[3] + "," + obj[4] + "&markers=size:mid"
})
}
});
console.log(location_events);
}
$('#calendar').fullCalendar({
header: '',
defaultDate: '2015-08-03',
defaultView: 'agendaDay',
allDaySlot: false,
slotEventOverlap: false,
events: location_events,
eventAfterRender: function(event, element, view) {
$(element).attr("id", "event_id_" + event.id);
}
});
}

Categories