Full Calendar static eventSources - fullcalendar

I am using fullcalendar eventSources to pull json event data from server. I have a variable sheet_id that changes and the selected_sheet_id() function will return the corresponding sheet selected. The problem is that when I call $("#calendar").fullCalendar('refetchEvents') to return events, sheet_id (thus all the events) are always the same. That is fullcalendar does not get refreshed with the current sheet_id before fetching events. How do I trigger the eventSources to "recompile" so that it pulls the correct sheet_id from the function before executing ajax call.
eventSources: [{
url: '/event/get_events',
type: 'GET',
data: {
sheet_id: selected_sheet_id()
},
error: function() {
alert('there was an error while fetching events!');
}
}]

First Try this with async:false for sync call :
eventSources: [
{
url: '/event/get_events',
type: 'GET',
async:false,
data:{
sheet_id: selected_sheet_id()
},
error: function() {
alert('there was an error while fetching events!');
},
},
]
Otherwise made one method which fetch event data in using Ajax call For ex :
var ajaxreturnstring="";
$.ajax({
type: "POST",
url: "/EMR-PHR/getPatientScheduleajax.html",
dataType:"html",
data: "",
async:false,
success: function(data){
ajaxreturnstring=$.trim(data);
var obj = eval("("+txt+")");
return obj;
},
error: function(e){
alert('Error: ' + e);
}
});
}

Related

Ajax data not passing to controller

I have a problem where the data in the ajax isn't passing the sessionStorage item. I have tried using JSON.stringify and added contentType: 'application/json' but still it's not passing. Can this be done using POST method? Also, I have debugged and returned those sessionStorages, hence the problem isn't because the sessionStorge doesn't contain data.
Here my function:
function functionA() {
$.ajax({
url: URLToApi,
method: 'POST',
headers: {
sessionStorage.getItem('token')
},
data: {
access_token: sessionStorage.getItem('pageToken'),
message: $('#comment').val(),
id: sessionStorage.getItem('pageId')
},
success: function () {
$('#success').text('It has been added!"');
},
});
}
Check below things in Controller's action that
there should be a matching action in controller
name of parameter should be same as you are passing in data in ajax
Method type should be same the ajax POST of the action in controller.
function AddPayment(id, amount) {
var type = $("#paymenttype").val();
var note = $("#note").val();
var payingamount = $("#amount").val();
$('#addPayment').preloader();
$.ajax({
type: "POST",
url: "/Fixed/AddPayment",
data: {
id: id,
amount: payingamount,
type: type,
note: note
},
success: function (data) {
}
});
}
Here is the working code from my side.
Check with this, and for the header part you need to get it from the Request in action
The solution to this problem has been found. The issue was the sessionStorage, hence I've passed it directly to the URL and now it working as follows:
function functionA() {
$.ajax({
url: 'http://localhost:#####/api?id=' + sessionStorage.getItem('pageId') + '&access_token=' + sessionStorage.getItem('pageToken') + '&message=' + $('#comment').val(),
method: 'POST',
headers: {
sessionStorage.getItem('token')
},
success: function () {
$('#success').text('It has been added!"');
},
});
}

Fullcalendar jquery plugin loading times after selecting and inserting new events

I am using fullcalendar plugin for our users to set their available times. Now everything works fine when reloading the page and when user adds one event, but when they add another event or start selecting, the page almost frozes. I tried all the solutions I found out on Stack but nothing.
I tried calendar.fullCalendar('addEventSource', response.new_events); to add only the new events returned, but lag persist. Tried removing all the eventRender functions, but still the same result. Only thing that seems to work is when I reload the page after each event insert.
IS there any way to decrease the lag while adding new eventSource after select?
These are the parts of my calendar js code
eventSources: [{
url: '/nanny/calendar/availability/all',
type: 'GET',
success: function (response) {
},
error: function (jqXhr, textStatus, errorThrown, data) {
$(".loading-icon").hide();
console.log(jqXhr, textStatus, errorThrown, data);
},
}],
eventRender: function (event, element) {
var delete_icon = '<i style="float: right; cursor: pointer;" class="' + event.icon + '"></i>';
if (event.icon) {
element.find("div.fc-time").append(delete_icon);
}
},
eventAfterRender: function (event, $el, view) {
$(".loading-icon").hide();
var formattedTime = $.fullCalendar.formatRange(event.start, event.end, "HH:mm");
// if event has fc-short class, data-start value will be displayed
// remove fc-short class and update fc-time span text
if ($el.is('.fc-short')) {
$el.find(".fc-time span").text(formattedTime + " - " + event.title);
$el.removeClass('fc-short');
$el.find('.fc-title').remove();
}
},
select: function (start, end) {
//in the past so give error
if (start.isBefore(moment())) {
$('#calendar').fullCalendar('unselect');
return false;
}
//get the event data
eventData = {
start: moment(start).format('YYYY-MM-DD HH:mm:ss'),
end: moment(end).format('YYYY-MM-DD HH:mm:ss')
};
if (eventData) {
if (eventData) {
$.ajax({
type: "POST",
url: "/nanny/calendar/store",
data: eventData,
dataType: "JSON",
success: function (response) {
console.log(response);
swal({
title: "Yay",
text: response.msg,
type: "success",
showCancelButton: false,
confirmButtonColor: "#e36159",
confirmButtonText: "CLose",
closeOnConfirm: false
});
calendar.fullCalendar('addEventSource', response.new_events);
},
error: function (jqXhr, textStatus, errorThrown, data) {
console.log(jqXhr, textStatus, errorThrown, data);
}
});
}
}
},
EDIT
Here's the video.
Lag example
A single event should be added using the renderEvent method. Create the event struct using the appropriate input and pass it to the renderEvent method.
$.ajax({
type: "POST",
url: "/nanny/calendar/store",
data: eventData,
dataType: "JSON",
success: function (response) {
var myEvent =
{
id: response.ID,
title: response.TITLE,
start: eventData.start,
end: eventData.end,
};
$( "#calendar" ).fullCalendar( "renderEvent", myEvent );
}
});
According to the documentation (https://fullcalendar.io/docs/event_data/Event_Object/) the start, end, and title attributes are required. If you are not collecting a title you can hardcode it to something such as "Event".
If you are updating your events in a db and want to allow your users to modify an event (ie. drag and drop, resize, etc.) without refreshing/reloading the calendar you must also provide the id attribute. This can be the unique key assigned to the meeting when stored in the database. You will want to pass this value back in the ajax response. If this functionality is not necessary, then you can ignore the id attribute.
**refetchEvents recall the function CalendarApp.prototype.init and refresh the calendar **
$.ajax({
url: "BASE_URL",
headers: {
Authorization: `Bearer ${token}`,
Accept: "application/json",
"Content-Type": "application/json"
},
type: "POST",
data: JSON.stringify(dataEvent),
dataType: "json",
contentType: "application/json",
success: function(data) {
window.swal({
title: "Checking...",
text: "Please wait",
buttons: false,
timer: 2000
});
$("#calendar").fullCalendar("refetchEvents",dataEvent);
}
});

Why does fullcalendar events with ajax not work?

I am trying to use an ajax call in the events option of fullcalendar with a json feed, but it's not working. I am working in an asp.net mvc4 application. My ajax call works fine, returns json as expected, but as a test I am just trying to create a local array, called events, add some sample data and pass it to the callback. But for some reason this does not get set in the fullcalendar code, and this does not show on the rendered calendar. I am debugging into the fullcalendar source, but haven't yet figured out why it's not getting set. Any ideas?
$('#calendar').fullCalendar({
theme: false,
timeFormat: '',
height: 'auto',
weekends: true,
events: function (start, end, callback) {
$.ajax({
type:'POST',
url: '#Url.Content("~/Home/GetJson")',
dataType: 'json',
data: {
start: start.toLocaleString("yyyy-mm-dd"),
end: end.toLocaleString("yyyy-mm-dd")
},
error: function (xhr, type, exception) { alert("Error: " + exception); },
success: function (response) {
var events = [];
events.push({
title: "new title",
start: "2014-11-05T13:15:30Z"
});
callback(events);
}
});
}
});
I have confirmed fullcalendar works if I pass in a json string in the events option like this
events:
[{ title: 'Event1', start: '2014-11-05T13:15:30Z' },
{ title: 'Event2', start: '2014-11-06T13:15:30Z' }]
Assuming you are using FullCalendar 2.*, the signature for events as a function is:
function( start, end, timezone, callback ) { }
As long as your event object is valid (you need to have a title and a start), your code should work if you change
events: function (start, end, callback) {
to
events: function (start, end, timezone, callback) {

Asynchronous ajax call causing issue in KnockOutjs

I have a button on click of that i am calling something like :
ViewModel:
self.MyArray = ko.observableArray();
self.remove = function(c) {
ko.utils.arrayForEach(c.sData(), function(ser) {
if (ser.Check() == true) {
self.MyArray.push(service);
count++;
}
});
if (count) {
$.ajax({
url: "/api/LoadCustomer/?reason=" + reason,
cache: false,
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: ko.toJSON(self.MyArray),
success: function(data) {
ko.utils.arrayForEach(self.MyArray(), function(removedata) {
c.sData.remove(removedata);
});
}
});
self.MyArray([]);
}
};
If i include async:false in my ajax call i get everything fine but if i didn't include async (its default property is true) i dont know somehow in my success function of ajax call self.MyArray() remains Empty but its not the case if i keep it false (Awkward).
Sometimes i fear like if i have series of ajax calls with async:true while loading into a observable array(OnLoad) there may be a slight chance of misplacement of data .
Help me understand .
The reason your observable array MyArray is empty sometimes is because this line of code self.MyArray([]); executing before the ajax call is done. How about this instead -
if (count) {
$.ajax({
url: "/api/LoadCustomer/?reason=" + reason,
cache: false,
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: ko.toJSON(self.MyArray),
success: function (data) {
ko.utils.arrayForEach(self.MyArray(), function (removedata) {
c.sData.remove(removedata);
});
},
complete: function() { // complete fires after success and error callbacks
self.MyArray([]); // empty the array no matter what happens (error or success)
}
});
}

Good way to enable auto refresh of events on the fullCalendar jquery plugin?

Is there a good way to have the fullCalendar jquery plugin auto-refresh its events?
I am able to simply call 'refetchEvents' using a timer, but that presents issues if the user is currently dragging an event (throwing javascript errors during the refresh while the event is dragged). Is there a better way?
Good solution... but is not enough:
var calE = {
url: 'calendarEvents.do',
type: 'POST',
data: {
siteId: $("#siteId").val()
},
error: function() {
alert('there was an error while fetching events!');
}
};
function loadCal(){
$('#calendar').fullCalendar({
theme: true,
events: calE,
editable: false,
eventDrop: function(event, delta) {
alert(event.title + ' was moved ' + delta + ' days\n' +
'(should probably update your database)');
},
loading: function(bool) {
if (bool) $('#loading').show();
else $('#loading').hide();
},
viewDisplay: function(viewObj) {}
});
}
function reloadCalendar(){
$('#calendar').fullCalendar('removeEventSource', calEvent );
var source = {
url: 'calendarEvents.do',
type: 'POST',
data: {
siteId: $("#siteId").val()
},
error: function() {
alert('there was an error while fetching events!');
}
};
$('#calendar').fullCalendar('removeEvents');
$('#calendar').fullCalendar('addEventSource', source );
$('#calendar').fullCalendar('rerenderEvents');
calE = source;
}
By using this you'll keep the original algorithm to fetch the data.
you'd just need to keep track of a flag, whether auto-refreshing should happen. it should be true by default, but set to false when dragging or resizing. you can set it based on the eventDragStart, eventDragStop, eventResizeStart, and eventResizeStop.
see http://arshaw.com/fullcalendar/docs/event_ui/ for a list of mouse-related triggers.

Resources