Fullcalendar - can't get events to show asp.net - javascript

I'm trying to implement fullcalender but I can't get the exemple data to show. I have been following this guide.
I get no errors but the events doesn't show in the calendar. I have tried different solutions but I can't get it to work, also my experience with json is very limited and i would appreciate some help.
public class CalendarController : BaseController
{
public ActionResult ShowCalendar()
{
return View();
}
public ActionResult GetMeetings(double start, double end)
{
using (var db = new ApplicationDbContext())
{
var fromDate = ConvertFromUnixTimestamp(start);
var toDate = ConvertFromUnixTimestamp(end);
var eventList = GetEvents();
var rows = eventList.ToArray();
return Json(rows, JsonRequestBehavior.AllowGet);
}
}
private static DateTime ConvertFromUnixTimestamp(double timestamp)
{
var origin = new DateTime(1970, 1, 1, 0, 0, 0, 0);
return origin.AddSeconds(timestamp);
}
private List<Events> GetEvents()
{
List<Events> eventList = new List<Events>();
Events newEvent = new Events
{
id = "1",
title = "Event 1",
start = DateTime.Now.AddDays(1).ToString("s"),
end = DateTime.Now.AddDays(1).ToString("s"),
allDay = false
};
eventList.Add(newEvent);
newEvent = new Events
{
id = "1",
title = "Event 3",
start = DateTime.Now.AddDays(2).ToString("s"),
end = DateTime.Now.AddDays(3).ToString("s"),
allDay = false
};
eventList.Add(newEvent);
return eventList;
}
<head>
#section scripts{
<link rel='stylesheet' href='fullcalendar/fullcalendar.css' />
<script src='lib/jquery.min.js'></script>
<script src='lib/moment.min.js'></script>
<script src='fullcalendar/fullcalendar.js'></script>
<script type="text/javascript">
$(document).ready(function () {
$('#calendar').fullCalendar({
theme: true,
header: {
left: 'prev, next, today',
center: 'title',
right: 'month, agendaWeek, agendaDay'
},
buttonText: {
prev: '<',
next: '>'
},
defaultView: 'month',
editable: false,
weekMode: 'liquid',
//allDaySlot: false,
selectTable: true,
//slotMinutes: 15,
events: function (start, end, timezone, callback) {
$.ajax({
url: "/calendar/getmeetings/",
type: 'GET',
dataType: 'json',
success: function (start, end, timezone, callback) {
alert('success');
},
error: function (start, end, timezone, callback) {
alert('there was an error while fetching events!');
},
data: {
// our hypothetical feed requires UNIX timestamps
start: start.unix(),
end: end.unix()
}
});
}
});
});
</script>
}
</head>
<br />
<div class="jumbotron">
<h1>Event Calendar</h1>
<div id="calendar"></div>
</div>

You are not following the tutorial particularly closely, I note, and are using a different methodology to fetch the events.
Within that, you simply forgot to pass the event list back to fullCalendar. You need to execute the callback function which fullCalendar provided to you, and supply your events to it.
Your definition of "success" and "error"'s callback parameters are nonsense, btw - you need to check the jQuery $.ajax documentation (http://api.jquery.com/jquery.ajax/) to see what is provided:
success: function (response) { //response will contain the JSON data from the server
callback(response); //pass the data to fullCalendar. You can pass "response" directly, assuming the response directly contains a JSON array of events
},
error: function(jqXHR) {
alert(jqXHR.responseText);
}
See https://fullcalendar.io/docs/event_data/events_function/ for more details.

You are not passing the events in a right way try passing the events my way its simple.If in case u still didn't get the calendar u need to check the console for some exception. Before passing the events u need the push the data to events.
event_array.push({
userid: v.UserId,
start: moment(v.LoginTime),
//end: moment(v.LogoutTime)
//start: moment(v.start),
end: v.LogoutTime != null ? moment(v.LogoutTime) : null
//color: v.themecolor,
//allday: v.isfullday
});
and then u need to call that in calender id for example
function GenerateCalender(event_array) {
debugger;
//$('#calender').fullCalendar('destroy');
$('#calender').fullCalendar({
events: event_array
});
}
This is my full code-
var event_array = [];
var event_array = [];
var selectedEvent = null;
FetchEventAndRenderCalendar();
function FetchEventAndRenderCalendar() {
events = [];
$.ajax({
url: "/Home/GetEvents",
data: "",
type: "GET",
dataType: "json",
async: false,
cache: false,
success: function (data) {
alert("success");
$.each(data, function (i, v) {
event_array.push({
userid: v.UserId,
start: moment(v.LoginTime),
//end: moment(v.LogoutTime)
//start: moment(v.start),
end: v.LogoutTime != null ? moment(v.LogoutTime) : null
//color: v.themecolor,
//allday: v.isfullday
});
})
GenerateCalender(event_array);
},
error: function (error) {
alert('failed');
}
})
}
function GenerateCalender(event_array) {
debugger;
//$('#calender').fullCalendar('destroy');
$('#calender').fullCalendar({
events: event_array
});
}

Related

How to call events method after new event source in FullCalendar.js?

I am trying to create a client side filter for events, I have gone with the same approach of addEventSource. I use the events method to conditionally render the events. I just wanna know how to call the events method or even redefine it?
This is the initial code I am using to render the the calendar
$('#calendar').fullCalendar({
header: {
left: 'prev,next today',
center: 'title',
right: 'month,basicWeek,basicDay'
},
displayEventTime: false,
navLinks: true, // can click day/week names to navigate views
editable: true,
eventLimit: true, // allow "more" link when too many events
events: (start, end, timezone, callback) => {
$.ajax({
url: 'get-events',
dataType: 'json',
data: {
// our hypothetical feed requires UNIX timestamps
start: start.unix(),
end: end.unix()
},
success: function (res) {
console.log(res)
var events = [];
res.map((value, index) => {
if (value.cadence != null) {
$("#allDropdown").append(`<a id="file-${value.dq_datafile_id}" onclick="selectThis(this)" href="#about">${value.data_file_name}</a>`)
}
if (value.cadence == "WEEKLY") {
if (value.dqfeed__file_status == "RECEIVED") {
const data_file_name = value.data_file_name;
let repeatDay = dow_handler.hasOwnProperty(data_file_name) ? dow_handler[data_file_name] : undefined
events.push({
title: `${value.data_file_name}`,
start: '2020-04-13',
dow: [repeatDay, 1],
color: '#00ff00'
});
}
});
});
});
This is the code I am using to fetch new events or filtered events
const applyCalendarFilter = () => {
var filter = {
type: 'get',
url: 'filter-events',
}
$("#calendar").fullCalendar('addEventSource', filter);
}
The error I get is Uncaught TypeError: Cannot read property 'hasTime' of undefined because the JSON returned doesn't have a start_date or end_date
So I found removeEvents that will clear all the events from the calendar and renderEvents that takes an option argument events and this will render the rest of the events.
So here's the code that did this.
const applyCalendarFilter = () => {
var filter = {
type: 'get',
url: 'filter-events',
}
$("#calendar").fullCalendar('removeEvents');
$.ajax({
url: 'filter-events',
type: 'get',
success: (res) => {
let events = [];
res.map((value, index) => {
if (value.cadence == "WEEKLY"){
events.push({
'title': value.title,
'start_date': value.start_date,
'end_date': value.end_date
}
})
$("#calendar").fullCalendar('renderEvents', events);
}, error: (res) => {
alert('cant get the data');
}
)};

Database with time in fullcalendar Not working

We are saved FromTime and ToTime value from database below attached image:
var events = [];
$.ajax({
type: "GET",
url: "/Booking/GetEvents",
success: function (data) {
$.each(data, function (i, v) {
events.push({
title: v.EventName,
description: v.Description,
start: moment(v.BookedFromDate).moment(v.FromTime),
end: v.BookedToDate != null ? moment(v.BookedToDate) : null,
name: v.ParticipantName,
className: 'event-red'
});
})
GenerateCalender(events);
},
error: function (error) {
alert('failed');
}
})
In this Code i need to get FromTime Value but in my code not working..
start: moment(v.BookedFromDate).moment(v.FromTime),
I need to display date and time

fullCalendar: Getting data from controller JSON

I am using the fullCalendar library in Visual Studio 2015. I am having trouble populating events from an AJAX command. No events are populating on the calendar. If I pass only one datetime and set allDay = true, it will populate the event. I need it to work with time as well and ave multiple events per day.
JS Code:
$(document).ready(function () {
$(".calendar").fullCalendar
({
header: {
left: 'month,basicWeek,basicDay,today',
center: 'title',
right: 'prev,next'
},
weekends: false,
eventLimit: true,
theme: true,
editable: false,
fixedWeekCount: false,
events: function(start, end, timezone, callback)
{$.ajax
({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "/Calendar/GetCalendarEvents",
dataType: 'json',
success: function (data)
{
var events = [];
$.each(data, function (index, value) {
events.push({
id: value['id'],
title: value['title'],
date: value['date']
//all data
});
console.log(value)
});
callback(events);
},
error: function (xhr, err) {
alert("ERROR! - readyState: " + xhr.readyState + "<br/>status: " + xhr.status + "<br/>responseText: " + xhr.responseText);
}
});
} });})
Note: The above code was one of may attempts to get it working. I have tried coding it differently before.
Controller Code:
public ActionResult GetCalendarEvents()
{
var events = new List<VMCalendarEvents>();
var db_events = db.PatientVisits.ToList();
foreach(var e in db_events)
{
DateTime visit_start = Convert.ToDateTime(e.VisitStart);
DateTime visit_end = Convert.ToDateTime(e.VisitEnd);
var calEvent = new VMCalendarEvents
{
id = e.PatientVisitID.ToString(),
title = "Placeholder Title" + e.PatientVisitID.ToString(),
date = visit_start.ToShortDateString(),
start = visit_start.ToString(),
end = visit_end.ToString(),
editable = true,
allDay = false
};
events.Add(calEvent);
}
var rows = events.ToArray();
return Json(rows, JsonRequestBehavior.AllowGet);}
Controller Code Output
JS Objects from Controller
EDIT: Problem Solved
So after some investigating I decided to use Razor in MVC to solve the problem. Instead of writing it into a seperate JS file, I put it into a header in the html file. By implementing the code below I was able to get the objects in the date formats of (yyyy-MM-ddTHH:dd & MM/dd/yyyy hh:mm tt):
$(function () {
$('#calendar').fullCalendar({
header: {
left: 'prev,next today',
center: 'title',
right: 'month,agendaWeek,agendaDay'
},
defaultDate: '2017-06-12',
editable: true,
events: '#Url.Action("GetCalendarEvents", "Calendar")',
});
});
I called the Controller using the URL Action command and return the JSON data as a ActionResult.
Fullcalendar might not like your slashes '/' in your date fields. Try hyphens '-' instead.
The documentation (https://fullcalendar.io/docs/utilities/Moment/) is more detailed about what formats for date/time work.
For reference, here is my fullcalendar code using JSON from AJAX (note that my events do not have an end time, but this was by choice):
{
$.ajax({
url: 'example.json',
dataType: 'json',
success: function(doc) {
var events = [];
$.each(doc, function(index, element) {
events.push({
title: element.title,
start: element.time,
url: element.url,
});
});
callback(events);
}
}) //ajax
}
And the JSON file (example.json):
[
{"time": "2017-06-06 09:00:00", "title": "Get It Done in June ", "url": "http://example.org"},
{"time": "2017-06-07 14:00:00", "title": "Fighting Imposter Syndrome for Dissertating Students ", "url": "http://example.com"},
{"time": "2017-06-14 14:00:00", "title": "Entering into the Academic Conversation", "url": "http://example.biz"}
]

FullCalendar events JSON feed with slightly different response format

I am using FullCalendar and this is how I initialise it:
$('#calendar').fullCalendar({
events: $('#calendar').data('source')
});
The problem is that the response is not in the format FullCalendar expects it as all the resultset is nested under data, i.e.
{
"data":
[
{
"title": "Event1",
"start": "2011-04-04"
},
{
"title": "Event2",
"start": "2011-04-04"
}
]
}
Is there a way I can provide a custom callback to make it use data element of the result as the event source?
I tried this
$('#calendar').fullCalendar({
events: function(start, end, timezone, callback) {
var url = $('#calendar').data('source');
$.get(url, {start: start, end: end, timezone: timezone})
.done(function( data ) {
callback(data.data);
});
}
});
But all I get is a JS error saying
moment.min.js:22Uncaught TypeError: Cannot read property '_calendar'
of undefined
I solved my problem. The error was coming not really from a FulLCalendar but Moment.js library
$('#calendar').fullCalendar({
events: function(start, end, timezone, callback) {
$.ajax({
url: $('#calendar').data('source'),
dataType: 'json',
data: {
start: start.format("YYYY-MM-DD"),
end: end.format("YYYY-MM-DD")
},
success: function(result) {
var events = [];
result.data.forEach(function(element) {
events.push({
title: element.title,
start: element.start
});
});
callback(events);
}
});
}
});

Displaying events in Fullcalendar jquery?

using a function on "events", i can't display my events, but if i use the string generated in console from using console.log of the same return variable, i can display my events. Why?
$(document).ready(function () {
var date = new Date();
var d = date.getDate();
var m = date.getMonth();
var y = date.getFullYear();
// page is now ready, initialize the calendar...
var calendar = $('#calendar');
calendar.fullCalendar({
// put your options and callbacks here
'theme': false,
'header': {
left: 'prev,next today',
center: 'title',
right: 'month,agendaWeek,agendaDay'
},
'weekends': false,
'defaultView': 'agendaDay',
axisFormat: 'HH:mm',
timeFormat: {
// for agendaWeek and agendaDay
agenda: 'H:mm{ - H:mm}', // 5:00 - 6:30
// for all other views
'': 'H(:mm)t' // 7p
},
minTime: 8,
ignoreTimezone: true,
editable: true,
selectable: true,
selectHelper: true,
select: function (startDate, endDate, allDay, jsEvent, view) {
/*
after selection user will be promted for enter title for event.
*/
var title = prompt('Event Title:');
/*
if title is enterd calendar will add title and event into fullCalendar.
*/
if (title) {
calendar.fullCalendar('renderEvent',
{
title: title,
start: startDate,
end: endDate,
allDay: allDay
},
true // make the event "stick"
);
}
calendar.fullCalendar('unselect');
},
eventDrop: function (event, delta) {
alert(event.title + ' was moved ' + delta + ' days\n' +
'(should probably update your database)');
},
events: function getjson() {
var out;
$.ajax({
url: 'http://localhost:8000/calendar/api/events/events/',
type: 'GET',
async: false,
success: function (data) {
out = JSON.stringify(data['objects']);
},
error: function () {
alert('errore');
}
});
console.log('hshshshshsh', out);
return out;
}
i'm using a json resource that displays event objects
You can enter the URL directly (as stated here):
calendar.fullCalendar({
events: 'http://localhost:8000/calendar/api/events/events/'
});
Following code is working for me..it may find you useful..just do changes according to your code
events: function (start, end, callback) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "Put your url here",
dataType: "json", // datatype returned by the webservice
success: function (data) {
var events = $.map(data.d, function (item, i) {
var event = new Object();
event.id = item.id;
event.start = new Date(item.date);
event.title = item.title;
event.color = item.color;
return event;
});
callback(events);
}, //end of Success function
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("StatusEvents: " + textStatus);
alert("Error: " + errorThrown);
}
}); //end of Ajax Function
} //end of events function
and my json entity is like
[Serializable]
public class Events
{
public int id { get; set; }
public string title { get; set; }
public DateTime date { get; set; }
public string color { get; set; }
}

Categories