FullCalendar events JSON feed with slightly different response format - javascript

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);
}
});
}
});

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');
}
)};

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

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
});
}

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"}
]

Issue in displaying events in Fullcalendar.js

Hi I am trying to implement FullCalendar.js with Asp.Net MVC. I am abl to show empty calendar but my events are not getting loaded in the Calendar.
$.ajax({
type: 'Get',
url: "/Matter/GetMatterEventsSummary",
data: data,
datatype: "Json",
contentType: "application/json",
success: function (doc) {
debugger;
$('#calendar').fullCalendar();
var events = [];
$(doc).find('[object Object],[object Object]').each(function () {
debugger;
events.push({
title: $(this).attr('title'),
start: $(this).attr('start') // will be parsed
});
// });
$('#calendar').fullCalendar('refetchEvents');
// callback(events);
}
});
it comes to success method and it has two events in it . but dont know why theseevents are not loaded into FullCalendar and also after this Calendar is not comingg automatically.
I guess it is not going in events.push. When I do hover on doc it shows "[object Object],[object Object]" and in this it has two records on [0] and [1].
Please help me in this.
Try using
$('#calendar').fullCalendar( 'rerenderEvents' )
after your events have been pulled.
Also, make sure to use the code from the official documentation properly. Try the following (untested):
$('#calendar').fullCalendar({
events: function(start, end, timezone, callback) {
$.ajax({
type: 'Get',
url: "/Matter/GetMatterEventsSummary",
data: data,
datatype: "Json",
contentType: "application/json",,
success: function(doc) {
var events = [];
$(doc).find('event').each(function() {
events.push({
title: $(this).attr('title'),
start: $(this).attr('start') // will be parsed
});
});
callback(events);
}
});
}
});
If you now want to refetch your events, call :
$('#calendar').fullCalendar('refetchEvents');
where necessary.
EDIT:
Since your are actually pulling data from a JSON feed, the following code may even be enough:
$('#calendar').fullCalendar({
events: '/Matter/GetMatterEventsSummary'
});
Check the documentation here:
EDIT2:
To dynamically modify the request you send to the backend (depending on a dropdown or something else), may be achieved as follows:
var myValue = 10;
$('#calendar').fullCalendar({
events: '/Matter/GetMatterEventsSummary',
data: function() { // a function that returns an object
return {
dynamic_value: myValue
};
}
});

fullcalendar js: fetching more events with ajax

I'm using fullcalendar,
how can I fetch more events from same server side, multiple urls?
The initial one works, I just want to add additional events when they arrive(ajax).
You could use Ajax to get the data and then add dynamically the new source
$.ajax({
url: "test.html",
success: function(data){
var source = { events: [
{
title: data.getTitle(),
start: new Date(year, month, day)
}
]};
$('#calendar').fullCalendar( 'addEventSource', source );
}
});
If each and every time you are using a different URL, then you can simply use addEventSource with the new URL.
If you are attempting to use the same URL, you can get all events (old and new) using refetchEvents.
You can also get the JSON and create the event as a client event using renderEvent. The latter is the most "ajax-y" of the options. In this case have your source return the JSON that represents the events, iterate through the array of new events, and call renderEvent on it.
// this call goes in a poll or happens when the something should trigger a
// fetching of new events
$.ajax({
url: "path/to/event/source",
success: function(data){
$.each(data, function(index, event)
$('#calendar').fullCalendar('renderEvent', event);
);
}
});
The ajax call done can also insert in the calendar code
$.ajax({
url: url,
type: 'GET',
data: { },
error: function() {
alert('there was an error while fetching events!');
}
}).done(function (doc) {
var event = Array();
$.each(doc, function(i, entry)
event.push({title: entry.title, start: entry.start});
});
$('#calendar').fullCalendar({
header: {
left: 'prev,next',
center: 'title',
right: 'month,agendaWeek,agendaDay'
},
defaultDate: '2014-06-12',
editable: true,
events: event
});
});

Categories