laravel: how to feed data in fullcalendar, fetched from database in controller - javascript

my Controller :
public function eventCalender(){
$eventCalender = [
'title' => 'Matts Booking',
'start' => '2019-05-05',
];
$response = [
'eventCalender' => $eventCalender,
'status' => 1,
];
return response()->json($response);
}
my js file :
function getEventCalender() {
var actionurl = base_url + "/events/event-calender";
$.ajax({
type: "GET",
url: actionurl,
success: function (res) {
if (res['status'] == 1) {
$("#event-list").hide();
$("#calender-list").show();
} else {
console.log("Something went wrong!!!!");
}
},
error: function (jqXHR, exception) {
$("#errormsg").show();
}
});
}
$(document).ready(function () {
getEventCalender();
document.addEventListener('DOMContentLoaded', function () {
var calendarEl = document.getElementById('calendar');
var calendar = new FullCalendar.Calendar(calendarEl, {
plugins: ['interaction', 'dayGrid', 'list', 'googleCalendar'],
header: {
left: 'prev,next today',
center: 'title',
right: 'dayGridMonth,listYear'
},
defaultDate: '2019-03-12',
navLinks: true,
businessHours: true,
editable: true,
event: res.eventCalender,
});
calendar.render();
});
});
so this is my controller and js file what i want is when i get data from controller how do i print that data in calendar ?
and i am using fullcalendar so when i add
document.addEventListener('DOMContentLoaded', function () { }
this function then only my calendar show in page.
If i put above function out of getEventCalender() function then my calender show perfectly but when i put it in getEventCalender() function like shown above it doesn't show my calendar.

Call the getEventCalender() in a document ready function to execute after all the content has loaded
$(function() {
getEventCalender();
})

Related

Fullcalendar 4: update info event from modal Bootstrap

I'm trying to update info date event from modal Bootstrap in Fullcalendar version 4.
My test:
Read event json
Click on event calendar, open modal, show info event and set value of a field with information to update
When I click on green button "Salva" (Save), doSubmitEdit function is called. It should:
close modal;
receive text field edited;
update via ajax my db;
update calendar event if necessary
But when then button is clicked I have this error:
q
TypeError: calendar.fullCalendar is not a function
on this line:
var event_obj_arr = calendar.fullCalendar('clientEvents', calendario_id);
(function ($) {
'use strict';
var calendarEl = document.getElementById('calendar');
var calendar = new FullCalendar.Calendar(calendarEl, {
locale: 'it',
plugins: ['dayGrid', 'timeGrid', 'list', 'interaction', 'bootstrap'],
themeSystem: 'bootstrap',
header: {
left: 'prev,next today',
center: 'title',
right: 'dayGridMonth,timeGridWeek,timeGridDay,listWeek'
},
navLinks: true, // can click day/week names to navigate views
selectable: true,
selectMirror: true,
editable: true,
eventLimit: true, // allow "more" link when too many events
events: {
url: '/_admin/vendor/fullcalendar/php/get-events.php',
failure: function () {
document.getElementById('script-warning').style.display = 'block';
}
},
eventClick: function (info) {
$('.card-body h4').html(info.event.start.toDateString());
$('.card-body p').html(info.event.title + '<br>' + info.event.extendedProps.autista + ' / Info: ' + info.event.extendedProps.autista_description);
$('#calendario_id').val(info.event.id);
$('#btnModal').trigger('click');
},
loading: function (bool) {
document.getElementById('loading').style.display =
bool ? 'block' : 'none';
}//,
});
calendar.render();
$('#submitButtonEdit').on('click', function (e) {
// We don't want this to act as a link so cancel the link action
e.preventDefault();
doSubmitEdit();
});
function doSubmitEdit() {
// get event object
var event_obj_arr = calendar.fullCalendar('clientEvents', calendario_id);
var event_obj = event_obj_arr[0];
// edit
$("#createEventModalEdit").modal('hide');
console.log($('#autista_description').val());
console.log($('#calendario_id').val());
// update event object properties
event_obj.extendedProps.autista_description = $('#autista_description').val();
// post to server
$.ajax({
url: '/_admin/vendor/fullcalendar/php/planning-aggiorna.asp',
data: 'type=changetitle&title=' + title + '&calendario_id=' + calendario_id,
type: 'POST',
dataType: 'json',
success: function (response) {
if (response.status == 'success') {
// nothing to do here
// update calendar, you may put this line into success method
calendar.fullCalendar('updateEvent', event_obj);
}
},
error: function (e) {
alert('Error processing your request: ' + e.responseText);
}
});
}
}).apply(this, [jQuery]);
Is it possibile to access fullcalendar class outside of it?
Thank you.
Here's the solution, thank to #Adison.
We have elements retrieved from modal form, update of live calendar (where I appended "changed" text to event's title) and update of db.
function doSubmitEdit() {
// get values from modal form
var calendario_id = $('#calendario_id').val();
var calendario_descrizione = $('#calendario_descrizione').val();
// get event object by id
var event = calendar.getEventById(calendario_id);
var title = event.title;
// post to server and update db
$.ajax({
url: '/_admin/planning-aggiorna.asp',
data: 'calendario_descrizione=' + encodeURIComponent(calendario_descrizione) + '&calendario_id=' + calendario_id,
type: 'POST',
dataType: 'text',
success: function (response) {
if (response == 'success') {
// update calendar
event.setProp('title', title + ' changed');
event.setExtendedProp('autista_description', calendario_descrizione);
}
},
error: function (e) {
alert('Error processing your request: ' + e.responseText);
}
});
}

Return the id from an ajax call into a button

I have an app that has a calendar which displays the details of an appointment.
I want to have it so when the user clicks the button, it will return the details of that particular appointment. I am using AJAX to call the details and jQuery to carry out the operations on my calendar.
Here is my AJAX call along with my jQuery:
#section Scripts{
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/fullcalendar/3.4.0/fullcalendar.min.js"></script>
$(document).ready(function () {
var events = [];
$.ajax({
type: "GET",
url: "/home/GetEvents",
success: function (data) {
$.each(data, function (i, v) {
events.push({
details: v.DetailsOfAppointment,
date: moment(v.DateOfAppointment),
room: v.RoomType,
confirmed: v.Confirmed,
church: v.Church.Name,
//color: v.ThemeColor,
parishAdmin: v.Admins.AdministratorName,
id: v.AppointmentId
});
})
GenerateCalender(events);
},
error: function (error) {
alert('failed');
}
})
function GenerateCalender(events) {
$('#calender').fullCalendar('destroy');
$('#calender').fullCalendar({
contentHeight: 400,
defaultDate: new Date(),
header: {
left: 'prev,next today',
center: 'title',
right: 'month,basicWeek,basicDay,agenda'
},
timeFormat: 'HH:mm',
eventLimit: true,
eventColor: events.color,
events: events,
eventClick: function (calEvent, jsEvent, view) {
$('#myModal #details').text(calEvent.details);
var $details = $('<div/>');
$details.append($('<p/>').html('<b>Date of Appointment : </b>' + calEvent.date.format("DD-MMM-YYYY HH:mm a")));
if (calEvent.end != null) {
$details.append($('<p/>').html('<b>End:</b>' + calEvent.end.format("DD-MMM-YYYY HH:mm a")));
}
$details.append($('<p/>').html('<b>Details : </b>' + calEvent.details));
$details.append($('<p/>').html('<b>Church Name : </b>' + calEvent.church));
if (calEvent.room != null)
{
$details.append($('<p/>').html('<b>Room : </b>' + calEvent.room));
}
else {
$details.append($('<p/>').html('<b>Room Not Confirmed'));
}
$details.append($('<p/>').html('<b>Parish Admin : </b>' + calEvent.parishAdmin));
if (calEvent.confirmed == true)
{
$details.append($('<p/>').html('<b>Status : Confirmed </b>'));
}
else
{
$details.append($('<p/>').html('<b>Status : Not Confirmed </b>'));
}
$('#myModal #pDetails').empty().html($details);
$('#myModal').modal();
}
})
}
})
I am just confused on how to get the AppointmentId out and create a button to bring the user to that particular appointment.

Bootstrap Popover with Ajax call not showing data

I can't seem to update the popovers contents with Ajax result.
ASP.Net (MVC4):
public ActionResult GetEmployeeDetails(string employeeId)
{
var contract = UnitOfWork.ContractRepository.ContractBusinessManager.GetContract(int.Parse(employeeId), DateTime.Now);
return PartialView("_EmployeeDetails", contract);
}
Html:
<a data-toggle-popup-employee-id="#evaluation.EmployeeId" >#evaluation.Employee.FullName.ToTitle()</a>
Javascript:
$(document).ready(function () {
$('[data-toggle-popup-employee-id]').popover(
{
html: true,
placement: 'top',
title: 'Title',
container: 'body',
content: function () {
//$(this).off('hover');
var employeeId = $(this).data('toggle-popup-employee-id');
$.ajax({
async: false,
url: '#Url.Action("GetEmployeeDetails", "Evaluation")',
data: { employeeId: employeeId },
success: function (result) {
return result;
//var html = result;
//$(this).contents.html = result;
},
error: function (xhr) {
alert(xhr.responseText);
}
})
},
trigger: 'hover'
});
});
The call works fine and gives back the partial result as html but the popovers content is still empty...
UPDATE:
It appears that every time I hover over the link, 10 [Object, HTMLAnchorElement]
are added directly to the $('[data-toggle-popup-employee-id]').
Each object has InnerText and InnerHtml set to the employees name...?
I'd personally do something like the following...
$(document).ready(function () {
$('[data-toggle-popup-employee-id]').on({
mouseenter: function () {
var originator = $(this);
var employeeId = originator.data('toggle-popup-employee-id');
$.get('#Url.Action("GetEmployeeDetails", "Evaluation")', { employeeId: employeeId }, function (data) {
originator.popover({
html: true,
placement: 'top',
title: 'Title',
container: 'body',
content: data,
}).popover('show');
})
},
mouseleave: function () {
//
// Destroy so the data will referesh
//
$(this).popover('destroy');
}
});
});
This way we are initialising the popover in the callback of the ajax request.
Hope this makes sense.
$('.popover.in .popover-inner').html(data);

ASP.Net MVC calling a controller action from FullCalendar's javascript function not loading the view

I am developing an ASP.Net MVC application. In one of my views, I am using FullCalendar control.
I am having 2 issues with my fullcalendar control -
My First issue is - On event click function, I am calling an action of some other controller from a Javasript function. My script is -
<script>
$(document).ready(function () {
var sourceFullView = { url: '/Calendar/GetDiaryEvents/' };
var sourceSummaryView = { url: '/Calendar/GetDiaryEvents/' };
var CalLoading = true;
$('#calendar').fullCalendar({
header: {
left: 'prev,next today',
center: 'title',
right: 'month'
},
defaultView: 'month',
editable: true,
allDaySlot: false,
selectable: true,
slotMinutes: 15,
events: '/Calendar/GetDiaryEvents/',
eventClick: function (calEvent, jsEvent, view) {
if (!confirm('You selected Election ID: ' + calEvent.title
+ "\nElection Date: " + calEvent.start.toDateString()
+ "\n\nDo you want to Vote for this Election?")) {
return;
}
var electionID = calEvent.id;
$.ajax({
url: '#Url.Action("Tally", "Voting")',
type: 'GET',
dataType: 'json',
cache: false,
data: { id: calEvent.id }
});
},
eventResize: function (event, dayDelta, minuteDelta, revertFunc) {
if (confirm("Confirm change appointment length?")) {
UpdateEvent(event.id, event.start, event.end);
}
else {
revertFunc();
}
},
viewRender: function (view, element) {
if (!CalLoading) {
if (view.name == 'month') {
$('#calendar').fullCalendar('removeEventSource', sourceFullView);
$('#calendar').fullCalendar('removeEvents');
$('#calendar').fullCalendar('addEventSource', sourceSummaryView);
}
}
}
});
CalLoading = false;
});
</script>
This is calling Tally method of VotingController -
[HttpGet]
public ActionResult Tally(int id)
{
return View(id);
}
When I debug through View of Tally then also it is looking fine but the new view called from action Tally is not loaded and browser still shows my calendar control.
My second issue is I want to display only monthly calendar. When I click next or prev button on calendar then my GetDiaryEvents function is called thrice.
Try to use a JsonResult in the Tally method. You could also render the view to string and include it in the json return.
[HttpGet]
public JsonResult Tally(int id)
{ //fill your model
return Json( new { viewdata=model } );
}
And in the ajax call return you just need to read json return object
success: function (return) {
$("#element").append(return.viewdata);
}

Pass variable from jQuery click function

I'm trying to pass a function from .click() function but for some reason I'm not getting the value. Here is my code,
<script>
var guyid;
$(document).ready(function() {
$('.guyid').click(function () {
guyid = $(this).attr('id'); //This variable needs to pass
alert(guyid);
});
$('#calendar').fullCalendar({
header: {
left: 'prev,next today',
center: 'title',
right: 'month,basicDay'
},
editable: true,
eventLimit: true, // allow "more" link when too many events
eventSources: ['json-script.php?id=' + guyid] //I need it here
});
});
</script>
How can I pass the variable from .click() function to the eventSources? Need this help badly. Tnx.
You need to destroy fullcalendar and re-initialize it.
Restores the element to the state before FullCalendar was initialized.
code
$(document).ready(function() {
$('.guyid').click(function() {
var guyid = $(this).attr('id');
$('#calendar')
.fullCalendar('destroy') //Destroy existing calendar
.fullCalendar({
header: {
left: 'prev,next today',
center: 'title',
right: 'month,basicDay'
},
editable: true,
eventLimit: true,
eventSources: ['json-script.php?id=' + guyid] //Set updated id
});
});
});
OR, You can use events (as a function) with refetchEvents
var guyid = 'something';
$('#calendar').fullCalendar({
events: function(start, end, timezone, callback) {
$.ajax({
url: 'json-script.php?id=' + guyid,
dataType: 'JSON',
success: function(doc) {
var events = [];
//Iterate are create
//This is pure hypothetical example
$(doc).find('event').each(function() {
events.push({
title: $(this).attr('title'),
start: $(this).attr('start') // will be parsed
});
});
callback(events);
}
});
}
});
$('.guyid').click(function () {
guyid = $(this).attr('id');
alert(guyid);
$('#calendar').fullCalendar('refetchEvents');
});

Categories

Resources