Fetching events on FullCalendar - javascript

I'm trying to make FullCalendar works on my app, but I'm not able to fetch the events I have on my mysql database. Here is my code:
.cshtml
<div class="panel-body">
<script type="text/javascript">
$(document).ready(function () {
$('#calendar').fullCalendar({
height: 600,
width: 500,
theme: false,
fixedWeekCount: false,
header: {
left: 'prev,next today',
center: 'title',
right: 'month,agendaWeek,agendaDay',
},
weekends: false,
editable: false,
eventSources: [
'Agenda/getEvents'
],
});
});
</script>
<div id="calendar"></div>
</div>
.cs controller
{
public class AgendaController : Controller
{
// GET: Agenda
public ActionResult Index()
{
return View();
}
public ActionResult Agenda()
{
ViewBag.id = Session["id"];
ViewBag.usuario = Session["usuario"];
ViewBag.tipo_usuario = Session["tipo_usuario"];
return View();
}
[HttpPost]
public JsonResult getEvents(double start, double end)
{
try
{
DataTable dt = new DataTable();
using (MySqlConnection con = new MySqlConnection(BD.CadConMySQL()))
{
using (MySqlCommand cmd = new MySqlCommand("SELECT tareas.tipo as title, tareas.fecha_inicio as start, tareas.fecha_fin as end FROM tareas", con))
{
using (MySqlDataAdapter da = new MySqlDataAdapter(cmd))
{
da.Fill(dt);
}
}
}
return Json(dt.ToList());
}
catch (Exception e)
{
RespGeneric resp = new RespGeneric("KO");
resp.msg = e.Message;
return Json(resp);
}
}
So the Agenda/getEvents give me back this following JSON that seems ok for FullCalendar:
JSON
However, the calendar doesnt show any event and I dont get why because the JSON looks good and if I fetch the events one by one on the .cshtml with exactly the same data it works.
Thanks!

I think that you didn't respect the structure of a standard eventSource fetch which is described in the documentation as :
$('#calendar').fullCalendar({
eventSources: [
// your event source
{
url: '/myfeed.php',
type: 'POST',
data: {
custom_param1: 'something',
custom_param2: 'somethingelse'
},
error: function() {
alert('there was an error while fetching events!');
},
color: 'yellow', // a non-ajax option
textColor: 'black' // a non-ajax option
}
// any other sources...
]
});

Related

Laravel Livewire: Possible to use AJAX?

The programming language we've used is: Laravel Livewire.
In the application there's 2 users: 1) Member; 2) Admin.
We have module called "Activities" where the admin can only create,read,update and inactive/active while the Member has a dashboard where they can see all active activities.
I implemented the fullCalendar, I managed to fetch and display the data. Now what I want is when the activity is clicked, it will show the activity details will using modal.
Controller
public function getActivityDetails(Request $request)
{
$data = $request->all();
$activity = Activity::where('id',$data['id']);
dd($activity);
return response()->json($activity);
}
View
<script>
$(document).ready(function(){
$.ajaxSetup({
headers:{
'X-CSRF-TOKEN' : $('meta[name="csrf-token"]').attr('content')
}
});
var activities = #json($activities);
var calendar = $('#calendar').fullCalendar({
header:{
left: 'prev,next today',
center: 'title',
right: 'month,agendaWeek, agendaDay'
},
events: activities,
selectable: true,
selectHelper: true,
selectable: true,
eventClick: function(event) {
if (event.id) {
$.ajax({
url: "/members-dashboard/getActivityDetails",
type: "POST",
data: {
id: event.id
},
success:function(data){
console.log(data);
}
})
}
}
// select: function(start, end, allDays){
// var value = $(this).val();
// console.log(value);
// $('#exampleModal').modal('toggle');
// }
});
function successResponse(data)
{
calendar.fullCalendar('refetchEvents');
}
});
</script>
WEB
use App\Http\Livewire\MembersPortal\MembersDashboard\ActivityDetails;
Route::post('/members-dashboard/getActivityDetails',MembersDashboard::class,'getActivityDetails')->middleware((['auth']));
NOTE: When I tried to console.log the data, it gives me all the html
Question: How can I return the value in my controller?
I think that you could use Two components
Activities an ActivitiyDetails components.
The first component will fetch all activities and eager loads activity details at the mount method.
$public Activity $activities;
public function mount(){
$this->activities= Activity::with('details')->where(...);
}
After that in your view you will have all your activities and the related activitities detail avoiding to use JQuery to fetch detail for each activity.
The second component could be ActivityDetail, which will accept a param of type ActivityDetail object.
In your view
<div>
#foreach ($activities as $activity)
<livewire:activity-detail :post="$activity->details">
#endforeach
</div>
I hope this help.

How to add remove event option with cross sign in fullcalendar.io ? asp.net mvc core

I am going to add remove cross sign with each event of calendar which are getting from database. But how to add this and i want when click on cross sign(delete) then specific url will be triggered and i want to delete event from database. Please let me know how can i do this? How to add delete event with cross sign.
call-init.js
!function($) {
"use strict";
var CalendarApp = function() {
this.$body = $("body")
this.$calendar = $('#calendar'),
this.$event = ('#calendar-events div.calendar-events'),
this.$categoryForm = $('#add-new-event form'),
this.$extEvents = $('#calendar-events'),
this.$modal = $('#my-event'),
this.$saveCategoryBtn = $('.save-category'),
this.$calendarObj = null
};
/* Initializing */
CalendarApp.prototype.init = function() {
this.enableDrag();
/* Initialize the calendar */
var events = [];
$.ajax({
type: 'POST',
async: false,
url: '/Booking/GetBookings',
success: function (mems) {
//states contains the JSON formatted list
//of states passed from the controller
$.each(mems, function (_, member) {
debugger;
events.push({
title: member.guestname,
start: new Date(member.checkindatetime),
end: new Date(member.checkoutdatetime),
allDay: true,
url: '/Booking/Booking/' + member.encryptedId,
className: member.classnamecolor
});
});
},
error: function (ex) {
alert('Buchungen konnten nicht geladen werden.');
}
});
var $this = this;
$this.$calendarObj = $this.$calendar.fullCalendar({
defaultView: 'month',
handleWindowResize: true,
header: {
left: 'prev,next today',
center: 'title',
right: ''
},
navLinks: false, // can click day/week names to navigate views
events: events
//eventStartEditable: false // disable drag&drop of events
});
},
//init CalendarApp
$.CalendarApp = new CalendarApp, $.CalendarApp.Constructor = CalendarApp
}(window.jQuery),
//initializing CalendarApp
function($) {
"use strict";
$.CalendarApp.init()
}(window.jQuery);
other calendar view is
#model FewoVerwaltung.Models.Booking.BookingListModel
<div id="calendar"></div>
<!-- Calendar JavaScript -->
<script src="~/plugins/calendar/dist/locale/de.js"></script>
<script src="~/plugins/calendar/dist/fullcalendar.min.js"></script>
<script src="~/plugins/calendar/dist/cal-init.js"></script>

FullCalendar not showing extraParams

I am having some problems retrieving these from my string
here is my script, taken from the website..
events: {
url: '/CalendarManager/Findall',
method: 'GET',
extraParams: {
custom_param1: 'customerName',
custom_param2: 'description'
},
failure: function () {
alert('there was an error while fetching events!');
},
eventRender: function (event, element) {
element.qtip({
content: event.custom_param1,
content: event.custom_param2
});
}
},
UPDATE: 12/24/2020
To answer questions below.. I am using 5.3.2 version. I can use this as well and it will bring back everything but the custom parameters.
events: '/CalendarManager/Findall',
I am using Json pulling from DB - Below is the code..
public ActionResult FindAll()
{
return Json(db.GetEvents.AsEnumerable().Select(e => new
{
id = e.CompanyId,
companyName = e.CompanyName,
title = e.Title,
description = e.Description,
allDay = e.AllDay,
start = e.StartDate.ToString("yyyy-MM-ddTHH:mm:ss"),
end = e.EndDate.ToString("yyyy-MM-ddTHH:mm:ss"),
color = e.Color
}).ToList(), JsonRequestBehavior.AllowGet);
}
I changed the version I was using and that is when the extras did not show up. So I added what I thought the documentation said to use.
Adding the extra Params after the url did not work..
UPDATE:
I read through the suggested. I guess I am still not understanding or maybe not getting "Where I am supposed to put the code".
I believe I need to use eventContent. I also did use the console.log(info.event.extendedProps.companyName); Which is great, it does show up in the console window, However i need it on the calendar not in the console window. FullCalendar's examples could be a little better!
Here is what I did but still does not show on the calendar.
eventDidMount: function (info) {
var tooltip = new Tooltip(info.el, {
title: info.event.extendedProps.description,
placement: 'top',
trigger: 'hover',
container: 'body'
});
console.log(info.event.extendedProps.companyName);
},
eventSources: [{
url: '/CalendarManager/Findall',
failure: function () {
alert('there was an error while fetching events!');
},
}],
eventContent: function (arg) {
html: arg.event.extendedProps.companyName
}
I did add some stuff in there to produce just a bubble when hovered over with this info but it does not work either.
Thank You!
UPDATE: 12/27/2020 Working Code
var calendar = new FullCalendar.Calendar(calendarEl, {
headerToolbar: {
left: 'prevYear,prev,next,nextYear today',
center: 'title',
right: 'dayGridMonth,dayGridWeek,dayGridDay,listWeek'
},
initialView: 'dayGridMonth',
navLinks: true, // can click day/week names to navigate views
editable: true,
dayMaxEvents: true, // allow "more" link when too many events
themeSystem: 'bootstrap',
selectable: true,
selectMirror: true,
//Random default events
//events: '/CalendarManager/Findall',
eventDidMount: function (info) {
var tooltip = new Tooltip(info.el, {
title: info.event.extendedProps.description,
placement: 'top',
trigger: 'hover',
container: 'body'
});
console.log(info.event.extendedProps.companyName);
},
events: {
url: '/CalendarManager/Findall',
failure: function () {
alert('there was an error while fetching events!');
},
},
eventContent: function (arg) {
return { html: arg.event.title + '<br>' + arg.event.extendedProps.companyName + '<br>' + arg.event.extendedProps.description };
}
});
calendar.render();
Thank you for all your help!
First, let me know what kind of version of fullcalendar you are using.
fullcalendar v5.5 doesn't provide eventRender.
And extraParams is not what you want to show. It is the query params which attach after the request url, like http://example.com/CalendarManager/Findall?custom_param1=customerName&....
If you want to use extend event props then you should parse them as extendProps.
And you should use Event Render Hooks rather than eventRender if you are using the latest version.
How to fix:
Anyway, you should use function, not an object.
You can use events (as a function)
function( fetchInfo, successCallback, failureCallback ) { }
You can also use events (as a json feed)
var calendar = new Calendar(calendarEl, {
events: '/myfeed.php'
});
If you are going to use object rather than function, then you can use eventSources
And if you want to handle the success response, then use eventSourceSuccess function
Here is an example (using fullcalendar v5.5):
document.addEventListener('DOMContentLoaded', function() {
var calendarEl = document.getElementById('calendar');
var calendar = new FullCalendar.Calendar(calendarEl, {
initialView: 'listWeek',
loading: function(bool) {
if (bool) {
$("#dashboard-calendar-column .pre-loader").show();
} else {
$("#dashboard-calendar-column .pre-loader").hide();
}
},
// get all events from the source
eventSources: [{
url: '/CalendarManager/Findall',
method: 'GET',
failure: function() {
document.getElementById('script-warning').style.display = 'block'
}
}],
// convert the response to the fullcalendar events
eventSourceSuccess: function(content, xhr) {
var events = [];
content.events.value.map(event => {
events.push({
id: event.id,
allDay: event.isAllDay,
title: event.subject,
start:event.start.dateTime,
end: event.end.dateTime,
// The followings are what you want to add as extended
custom_param1: 'customerName',
custom_param2: 'description',
// Or you could add them to the extendedProps object
extendedProps: {
custom_param1: 'customerName',
custom_param2: 'description',
description: event.bodyPreview,
...
},
// You can check fullcalendar event parsing
...
})
})
return events;
},
eventDidMount: function (arg) {
// remove dot between the event titles
$(arg.el).find('.fc-list-event-graphic').remove();
// You can select the extended props like arg.event.custom_param1 or arg.event.extendProps.custom_param1
...
},
});
calendar.render();
})
Hope this would help you.
You can use extraParams using eventSources if you are using fullcalendar v5.
eventSources: [{
url: '/CalendarManager/Findall',
method: 'POST',
extraParams: {
custom_param1: 'customerName',
custom_param2: 'description'
}
...
}]
You should use POST rather use GET, then it will work.

Displaying data on Full Calendar using Ajax not displaying records

I have created a Full Calendar and using ajax to populate the events from a database tables.
I can get the graph showing however it isn't populating the events from the database, instead it is showing todays date and time and only one event.
I'm not sure what I'm doing wrong.
I'm following this tutorial:
http://www.dotnetawesome.com/2017/06/event-calendar-in-aspnet-mvc.html
What is
currently displaying
Script which is in my Layout page
<script>
$(document).ready(function () {
var events = [];
$.ajax({
type: "GET",
url: "/Calendar/Schedules",
success: function (data) {
$.each(data, function (i, v) {
events.push({
title: v.Subject,
description: v.Description,
start: moment(v.Start),
end: v.EndTime != null ? moment(v.EndTime) : null,
color: v.ThemeColor,
allDay: v.IsFullDay
});
})
GenerateCalender(events);
},
error: function (error) {
alert('failed');
}
})
function GenerateCalender(events) {
$('#calender').fullCalendar('destroy');
$('#calender').fullCalendar({
contentHeight: 400,
defaultDate: new Date(),
timeFormat: 'h(:mm)a',
header: {
left: 'prev,next today',
center: 'title',
right: 'month,basicWeek,basicDay,agenda'
},
eventLimit: true,
eventColor: '#378006',
events: events
})
}
});
</script>
Get method under the Calendar Controller
public JsonResult Schedules()
{
var schedules = _context.Schedules.ToList();
var result = new JsonResult(new { Data = schedules});
return new JsonResult(result.Value);
}
however it isn't populating the events from the database
Note that you're following an old tutorial for ASP.NET Classic instead of ASP.NET Core. And the way we return a JsonResult has changed:
public JsonResult Schedules()
{
var schedules = _context.Schedules.ToList();
var result = new JsonResult(new { Data = schedules});
return new JsonResult(result.Value);
return new JsonResult(schedules);
}
Today we don't need specifiy a Data property for JsonResult anymore. Instead, simply construct a JsonResult by new JsonResult(the_data).
The second issue is, the returned json by default is Camel-Cased if you're using ASP.NET Core 3.1. However, it's likely that your javascript code assumes that the JSON returned by server is Pascal-Cased. If that's the case, change your js code as below:
events.push({
title: v.Subject,
title: v.subject,
description: v.Description,
description: v.description,
start: moment(v.Start),
start: moment(v.start),
end: v.EndTime != null ? moment(v.EndTime) : null,
end: v.endTime != null ? moment(v.endTime) : null,
color: v.ThemeColor,
color: v.themeColor,
allDay: v.IsFullDay
allDay: v.isFullDay
});

Bind Webgrid using JQuery failed

Hi I am using webgrid this time.and Binding json data using JQuery. My ajax call script providing data but I am unable to get it some how.I have gone thorugh all the questions available here but nothing worked. Look at the components and tell me what is wrong.
This is the web grid
<div id="GridContent">
#{
var grid = new WebGrid(Model, canPage: true, rowsPerPage: 15, selectionFieldName: "Id", ajaxUpdateContainerId: "GridContent", canSort: true);
}
#grid.GetHtml(
tableStyle: "webgrid-table",
rowStyle: "webgrid-row-style",
htmlAttributes:"grid",
emptyRowCellValue: "--",
headerStyle: "webgrid-header",
selectedRowStyle: "webgrid-alternating-row",
columns: grid.Columns(
grid.Column(columnName: "CenterId", header: "Id"),
grid.Column(columnName: "CenterName", header: "CenterName"),
grid.Column(columnName: "CenterCode", header: "CenterCode"),
grid.Column(columnName: "Address", header: "Address"),
grid.Column(columnName: "EmailId", header: "EmailId"),
grid.Column(format: #<a id="EditCenter" class="fa-anchor" data-id="#item.CenterId">Edit</a>),
grid.Column(format: (item) => Html.ActionLink((string)"Delete", "DeleteCenter", new { CenterId = item.CenterId }, new { id = "DeleteCenter", onclick = "return confirm('Are You Sure Want To Delete The Center Data?');" }))))
</div>
and here is my ajax call for binding the data on dropdown change.
$(document).ready(function () {
$("#ListType").change(function () {
var webgrid;
$.ajax({
type: 'POST',
url: ListTypeUrl,
data: { id: $("#ListType").val() },
datatype:'html',
success: function (result) {
$("#GridContent").html(result);
alert("Success");
},
error: function (result) {
alert("On select Failed " + result);
}
});
})
});
Here is Controller method for getting JSON Results
public JsonResult GetCenterList(int id)
{
List<CenterDetails> cd = objDal.GetCenterListItem(id.ToString(), Session["AgentId"].ToString());
return Json(cd,JsonRequestBehavior.AllowGet);
}
public List<CenterDetails> GetCenterListItem(string type, string AgentId)
{
XElement xl = new XElement("root"
, new XAttribute("OType", "Select")
, new XAttribute("Target", "CenterList")
, new XElement("Type",Convert.ToInt32(type))
, new XElement("AgentId", AgentId));
ds = ExecuteDataSet("Sp_CenterAction", CommandType.StoredProcedure, new MySqlParameter("#xml", xl.ToString()));
dt = ds.Tables[0];
drc = dt.Rows;
List<CenterDetails> objList = new List<CenterDetails>();
foreach (DataRow dr in drc)
{
objList.Add(new CenterDetails
{
CenterId = Convert.ToInt32(dr["cm_Id"].ToString()),
CenterName = dr["cm_Name"].ToString(),
CenterCode = dr["cm_CenterCode"].ToString(),
Address = dr["cm_Address"].ToString(),
EmailId = dr["cm_EmailId"].ToString()
});
}
return objList;
}

Categories