FullCalendar - None Standard Field with addEventSource - asp.net

Getting JSON from CodeBehind with additional None Standard fields using ASP.NET.
Im getting the "standard" title,start,end,color,ClassName correctly when passing "obj" to addEventSource.
The problem is that i would like to use the "Events" and "eventRender" instead of using "addEventSource" to be able to handle the None Standard fields, this doesn't work.
Is it possible to pass object or JSON to "Events"?
I have also tried to use the "docd" (the none parseJSON string) not getting any results displayed in the calendar. Using FullCalendar 3
ex.
events: obj,
eventRender: function(event, element) {
Console.log(info.event.extendedProps.PrjectID)
}
This is request Ajax:
$.ajax({
type: "POST",
url: "Calender.aspx/GetTimeData",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ 'year': year, 'month': month, 'projectID': projectid }),
dataType: "json"
}).done(function (doc) {
var events = [];
docd = doc.d;
obj = $.parseJSON(doc.d);
}
});
ExtraParameters:
ProjectID,UserID,WorkTypeID,Signed
Json:
[{"Signed":1,"ProjectID":39,"WorkTypeid":1,"UserID":97,"id":719627,"start":"2019-01-01T07:00:00","end":"2019-01-01T15:00:00","title":"Test Title ","color":"#607d8b","className":null}]
********************* UPDATE 1 *********************
Edited the code, the ajax request works without any problems when implemented within the fullcalendar environment, BUT the posts will not appear in the calendar, also the "eventRender" is not triggered.
$('#calendar').fullCalendar({
loading: function (bool) {
//LoadEvents();
//alert('events are being rendered'); // Add your script to show loading
},
eventAfterAllRender: function (view) {
//alert('all events are rendered'); // remove your loading
},
navLinks: true,
lazyFetching: false,
height: "auto",
aspectRatio: 2,
weekends: true,
weekNumbers: true,
displayEventEnd: true,
showNonCurrentDates: false,
weekLabel: "V",
allLocales: true,
locale: "sv",
header: false,
//header: {
// //left: 'prev,next today',
// left: '',
// center: '',
// right: 'month,agendaWeek,agendaDay,listMonth'
//},
viewRender: function (element, view) {
var title = view.title;
$("#CalendarHeadTitle").html(title);
//element.find('.fc-title').append("-test-");
},
dayClick: function (date, jsEvent, view) {
$("#sDate, #eDate").val(moment(date).format("YYYY-MM-DD"));
$('.modal').modal('show');
},
eventClick: function (info) {
$('.modal').modal('show');
},
eventDrop: function (event, delta, revertFunc) {
//TODO: Implement - call to move!
if (!confirm("Vill du flytta ")) {
revertFunc();
}
},
editable: true,
events: function (start, end, timezone, callback) {
$.ajax({
type: "POST",
url: "Calender.aspx/GetTimeData",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ 'year': $("#<%=DdlYear.ClientID%>").val(), 'month': $("#<%=DdlMonth.ClientID%>").val(), 'projectID': $("#<%=DdlProjects.ClientID%>").val() }),
dataType: "json"
}).done(function (doc) {
var events = $.parseJSON(doc.d);
console.log(doc.d);
callback(events); //this provided callback function passes the event data back to fullCalendar
});
},
eventRender: function (event, element) {
console.log('event render action');
}
});

I think you are mixing up the syntax and functionality of fullCalendar 3 and fullCalendar 4. They are very different.
Console.log(info.event.extendedProps.PrjectID)
will fail because
a) you haven't defined an info variable in your function parameters (so you should be getting a Console error, although you didn't mention one), and
b) even if you fix that, I strongly suspect (based on the signature you've used for your eventRender function, and the fact you're making extensive use of jQuery) that you're actually using fullCalendar 3, whose event object doesn't have an "extendedProps" property.
If my assumption is correct then I would expect
console.log(event.ProjectID);
to output the required data.
P.S. Your code is shown somewhat out of context, so I'm not sure exactly how you're going about loading the events, but you don't need to have a process where you make an AJAX call outside the calendar environment, and then pass the resulting array to the calendar later. Instead, use one of fullCalendar's built-in features for dealing with dynamic event sources. In your case, the events-as-a-function option is probably the most suitable.
This is the recommended way to connect your data to the calendar.
You can implement it like this:
events: function( start, end, timezone, callback ) {
$.ajax({
type: "POST",
url: "Calender.aspx/GetTimeData",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ 'year': year, 'month': month, 'projectID': projectid }),
dataType: "json"
}).done(function (doc) {
var events = $.parseJSON(doc.d);
callback(events); //this provided callback function passes the event data back to fullCalendar
});
}
FullCalendar will run this code every time it needs new events (e.g. when the calendar loads, and whenever the user changes the calendar view to cover a date range for which it hasn't already fetched events). As you can see, fullCalendar provides you with start and end dates via the callback parameters, which you can pass directly to your server to help it filter the list of events it returns to cover the date range required. Your code currently accepts "month" and "year", so could get those from the start date passed in, but if you are using anything other than "month" views then this won't be flexible enough.

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

JQuery AutoComplete updating multiple fields ASP.NET

I'm trying to use the AutoComplete feature of JQuery to update multiple fields on an ASP.NET web page. The individual textbox is functioning perfectly, but I cannot figure out how to update multiple textboxes on the page once the user selects.
I've read many suggestions here that state I need to implement a result handler, but my intellisense is not showing that as an option, and IE I get a JS error saying that the object doesn't support this method.
I am linking to jquery-1.4.2.min.js and jquery-ui-1.8.5.custom.min.js
Here's my code:
$(function () {
$("#Street1").autocomplete({
source: function (request, response) {
$.ajax({
url: "/address/FindAddress", type: "POST", dataType: "json",
data: { startAddress: request.term },
success: function (data) {
response($.map(data, function (item) {
return { label: item.DisplayText, value: item.ValueText, id: item.ID }
}))
}
})
} /* End source: function */
})
.result(function (event, data, formatted) {
$("#Street2").val("test");
})
/* end Autocomplete */
}); /* Function */
In this case you'd want the select handler, like this:
$("#Street1").autocomplete({
source: function (request, response) {
$.ajax({
url: "/address/FindAddress", type: "POST", dataType: "json",
data: { startAddress: request.term },
success: function (data) {
response($.map(data, function (item) {
return { label: item.DisplayText, value: item.ValueText, id: item.ID }
}));
}
});
},
select: function( event, ui ) {
$("#Street2").val(ui.item.label); //or ui.item.value
}
});
I'm not sure if you want the label, value or id in there, just use ui.item.whatever. Using select, whatever a value is chosen you can populate the #Street2 field as well.
view the source of this example, it's exactly what you want (look at the select method) : http://jqueryui.com/demos/autocomplete/#custom-data
Also, it's JavaScript, don't rely on intellisense.
EDIT: I pasted the wrong link

Resources