Displaying events in Fullcalendar jquery? - javascript

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

Related

Calendar::gotoDate method recalls the ajax request defined in the events

I'm using fullCalendar v5 and I configured it to bind the events using an AJAX call.
Let's assume we are in Jan month 2022, if the AJAX call (http://blahblah.com//ReportDates) will return the JSON data with some date values.
Let's say the JSON data has 2021-08-01. Now when I try to change the calendar to go to Aug 1st 2021 date using the in-built method, the AJAX call (http://blahblah.com//ReportDates) will happen once again.
How can I prevent the second call ?
function calendarLoad(ReportID, ReportDate, isInitialLoad) {
try {
var date = new Date();
var lastDay = new Date(date.getFullYear(), date.getMonth() + 1, 0);
var calendarEl = document.getElementById('calendar');
if (calendarEl != null) {
calendar = new FullCalendar.Calendar(calendarEl, {
initialView: 'dayGridMonth',
validRange: function() {
return {
start: '2016-01-01', //setting the start date to Jan 1st
end: lastDay // setting the end date based on the current date
};
},
headerToolbar: {
left: 'prev',
center: 'title',
right: 'next'
},
events: function(fetchInfo, successCallback, failureCallback) {
var dt;
if (ReportDate == '') {
dt = fetchInfo.startStr.split('T')[0];
} else {
dt = ReportDate;
}
var events = [];
$.ajax({
url: "http://blahblah.com//ReportDates",
type: 'GET',
dataType: 'JSON',
data: {
reportID: ReportID,
startDate: isInitialLoad == true ? '' : dt
},
success: function(response) {
$.map(response, function(r) {
events.push({
id: r.title,
title: 'Available',
start: r.Rpt_Date,
allDay: true,
url: 'http://blahblah.com/Index/?reportID=' + btoa(ReportID) + '&reportDate=' + btoa(r.Rpt_Date),
});
});
successCallback(events);
if (response.length > 0) {
// assigning the latest report date as initial date for calendar, this date is fetched from the ajax response
// This method is making the ajax call once again, I just need to navigate to JSON data date and don't make the
// ajax call once again. Rest all clicks on the calendar should work as usual after the initial load.
calendar.gotoDate(response[0].Rpt_Date);
} else {
calendar.gotoDate(dt);
}
},
error: function(xhr) {
alert('Error while loading the calendar!!!');
}
});
},
eventClick: function(event) {
if (event.event.url) {
event.jsEvent.preventDefault();
window.open(event.event.url, 'RHS',
'toolbar=0,scrollbars=1,location=No,statusbar=0,menubar=1,resizable=1,width=1050,height=590,left=50,top=50');
}
}
});
}
calendar.render();
} catch (e) {
alert(e);
}
}

Need help figuring out why Fullcalendar isn't showing my events. - no errors showing

I am using Laravel 7. I followed the instructions from the Fullcalendar website and have searched for days trying to figure this out.
For some reason, I can't pull or save data. I've tried doing a die-dump and it's like the code isn't firing. Maybe someone can see something I'm missing. I am using the cdn's for ajax, jquery and fullcalendar.
Here is the code for the controller:
public function index()
{
if(request()->ajax())
{
$start = (!empty($_GET["start"])) ? ($_GET["start"]) : ('');
$end = (!empty($_GET["end"])) ? ($_GET["end"]) : ('');
$data = Event::whereDate('start', '>=', $start)->whereDate('end', '<=', $end)->get(['id','title','start', 'end']);
return Response::json($data);
}
return view('calender');
}
public function create(Request $request)
{
$insertArr = [ 'title' => $request->title,
'start' => $request->start,
'end' => $request->end
];
$event = Event::insert($insertArr);
return Response::json($event);
}
public function update(Request $request)
{
$where = array('id' => $request->id);
$updateArr = ['title' => $request->title,'start' => $request->start, 'end' => $request->end];
$event = Event::where($where)->update($updateArr);
return Response::json($event);
}
public function destroy(Request $request)
{
$event = Event::where('id',$request->id)->delete();
return Response::json($event);
}
Here is the script from the view:
$(document).ready(function () {
var SITEURL = "{{url('/')}}";
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
var calendar = $('#calendar').fullCalendar({
editable: true,
events: SITEURL + "calendar",
displayEventTime: true,
editable: true,
eventRender: function (event, element, view) {
if (event.allDay === 'true') {
event.allDay = true;
} else {
event.allDay = false;
}
},
selectable: true,
selectHelper: true,
select: function (start, end, allDay) {
var title = prompt('Event Title:');
if (title) {
var start = $.fullCalendar.formatDate(start, "Y-MM-DD HH:mm:ss");
var end = $.fullCalendar.formatDate(end, "Y-MM-DD HH:mm:ss");
$.ajax({
url: SITEURL + "calendar/create",
data: 'title=' + title + '&start=' + start + '&end=' + end,
type: "POST",
success: function (data) {
displayMessage("Added Successfully");
}
});
calendar.fullCalendar('renderEvent',
{
title: title,
start: start,
end: end,
allDay: allDay
},
true
);
}
calendar.fullCalendar('unselect');
},
eventDrop: function (event, delta) {
var start = $.fullCalendar.formatDate(event.start, "Y-MM-DD HH:mm:ss");
var end = $.fullCalendar.formatDate(event.end, "Y-MM-DD HH:mm:ss");
$.ajax({
url: SITEURL + 'calendar/update',
data: 'title=' + event.title + '&start=' + start + '&end=' + end + '&id=' + event.id,
type: "POST",
success: function (response) {
displayMessage("Updated Successfully");
}
});
},
eventClick: function (event) {
var deleteMsg = confirm("Do you really want to delete?");
if (deleteMsg) {
$.ajax({
type: "POST",
url: SITEURL + 'calendar/delete',
data: "&id=" + event.id,
success: function (response) {
if(parseInt(response) > 0) {
$('#calendar').fullCalendar('removeEvents', event.id);
displayMessage("Deleted Successfully");
}
}
});
}
}
});
});
function displayMessage(message) {
$(".response").html("<div class='success'>"+message+"</div>");
setInterval(function() { $(".success").fadeOut(); }, 1000);
}
Finally figured this out. Thanks to everyone that responded! Once I started a new Laravel project, I was able to pinpoint what I was missing.
It turns out that there were a couple issues:
The first one was that the docs on the Fullcalendar.io website weren't very helpful. It gives you a place to start, but then you are on your own to figure out what's missing in the code. My code needed this added to the script in the view:
var calendar = new Calendar(calendarEl, {
events: '/myurlfeed.php'
});
The second is that the tutorial I followed included an if statement saying that if it was ajax, then execute code. Once I took out the if portion, it directly accessed the code and was able to load from the database. Whew! Lots of hours spent trying to figure this out.

Double entry on switching form day to week or month in fullcalendar

I have an issue when I try to scroll to other views on fullcalendar and trying switch form day to week or month in fullcalendar is sows double entries when I make only one entry and when my next action is to switch views. This is not recorded to database and once I logout and login again the issue is gone. So this is in the viewer but i don't know exactly where to go to fix it. Any suggestions?
This Picture show the issue in viewer when i add only one entrly and scrolling the views shows two entries:
My HTML code contains Modals as well. I can post it, if it is required.
I use Latest version of full calendar.
The full calendar javascript code is:
$(document).ready(function () {
var calendar = $('#calendar').fullCalendar({
header: {
left: 'prev,next today',
center: 'title',
right: 'agendaDay,agendaWeek,month'
},
defaultView: 'agendaDay',
editable: true,
selectable: true,
allDaySlot: false,
displayEventTime: false,
slotDuration: '02:00:00',
contentHeight: 'auto',
longPressDelay: 10,
eventLongPressDelay: 20,
selectLongPressDelay: 25,
events: "index.php?view=1",
eventAfterRender: function (event, element, view) {
if (parseInt(event.title) >= 180) {
element.css('background-color', '#F27F0C');
element.css('color', '#000000');
element.css('padding-left', '0.17em');
//element.css('text-align','center');
element.css('font-size', '1.47em');
},
eventClick: function (event, jsEvent, view) {
endtime = $.fullCalendar.moment(event.end).format('h:mm');
starttime = $.fullCalendar.moment(event.start).format('dddd, MMMM Do YYYY, h:mm');
var mywhen = starttime + ' - ' + endtime;
$('#modalTitle').html(event.title);
$('#modalWhen').text(mywhen);
$('#eventID').val(event.id);
$('#calendarModal').modal();
},
select: function (start, end, jsEvent) {
endtime = $.fullCalendar.moment(end).format('h:mm');
starttime = $.fullCalendar.moment(start).format('dddd, MMMM Do YYYY, h:mm');
var mywhen = starttime + ' - ' + endtime;
start = moment(start).format();
end = moment(end).format();
$('#createEventModal #startTime').val(start);
$('#createEventModal #endTime').val(end);
$('#createEventModal #when').text(mywhen);
$('#createEventModal').modal('toggle');
},
eventDrop: function (event, delta) {
$.ajax({
url: 'index.php',
data: 'action=update&title=' + event.title + '&start=' + moment(event.start).format() + '&end=' + moment(event.end).format() + '&id=' + event.id,
type: "POST",
success: function (json) {
//alert(json);
}
});
},
eventResize: function (event) {
$.ajax({
url: 'index.php',
data: 'action=update&title=' + event.title + '&start=' + moment(event.start).format() + '&end=' + moment(event.end).format() + '&id=' + event.id,
type: "POST",
success: function (json) {
//alert(json);
}
});
}
});
$('#submitButton').on('click', function (e) {
e.preventDefault();
doSubmit();
});
$('#deleteButton').on('click', function (e) {
// We don't want this to act as a link so cancel the link action
e.preventDefault();
doDelete();
});
function doDelete() {
$("#calendarModal").modal('hide');
var eventID = $('#eventID').val();
$.ajax({
url: 'index.php',
data: 'action=delete&id=' + eventID,
type: "POST",
success: function (json) {
if (json == 1)
$("#calendar").fullCalendar('removeEvents', eventID);
else
return false;
}
});
}
function doSubmit() {
$("#createEventModal").modal('hide');
var title = $('#title').val();
var startTime = $('#startTime').val();
var endTime = $('#endTime').val();
$.ajax({
url: 'index.php',
data: 'action=add&title=' + title + '&start=' + startTime + '&end=' + endTime,
type: "POST",
success: function (json) {
$("#calendar").fullCalendar('renderEvent',
{
id: json.id,
title: title,
start: startTime,
end: endTime
},
true);
}
});
}
});
Ok! Finally I find it out. I have to add two lines of code in the doSubmit function the code is : $('#calendar').fullCalendar('removeEvents'); , $('#calendar').fullCalendar('refetchEvents');
And the function so far:
function doSubmit() {
$("#createEventModal").modal('hide');
var title = $('#title').val();
var startTime = $('#startTime').val();
var endTime = $('#endTime').val();
$.ajax({
url: 'index.php',
data: 'action=add&title=' + title + '&start=' + startTime + '&end=' + endTime,
type: "POST",
success: function (json) {
$("#calendar").fullCalendar('renderEvent',
{
id: json.id,
title: title,
start: startTime,
end: endTime
},
true);
$('#calendar').fullCalendar('removeEvents');
$('#calendar').fullCalendar('refetchEvents');
}
});
}

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

Categories