fullcalendar js: fetching more events with ajax - javascript

I'm using fullcalendar,
how can I fetch more events from same server side, multiple urls?
The initial one works, I just want to add additional events when they arrive(ajax).

You could use Ajax to get the data and then add dynamically the new source
$.ajax({
url: "test.html",
success: function(data){
var source = { events: [
{
title: data.getTitle(),
start: new Date(year, month, day)
}
]};
$('#calendar').fullCalendar( 'addEventSource', source );
}
});

If each and every time you are using a different URL, then you can simply use addEventSource with the new URL.
If you are attempting to use the same URL, you can get all events (old and new) using refetchEvents.
You can also get the JSON and create the event as a client event using renderEvent. The latter is the most "ajax-y" of the options. In this case have your source return the JSON that represents the events, iterate through the array of new events, and call renderEvent on it.
// this call goes in a poll or happens when the something should trigger a
// fetching of new events
$.ajax({
url: "path/to/event/source",
success: function(data){
$.each(data, function(index, event)
$('#calendar').fullCalendar('renderEvent', event);
);
}
});

The ajax call done can also insert in the calendar code
$.ajax({
url: url,
type: 'GET',
data: { },
error: function() {
alert('there was an error while fetching events!');
}
}).done(function (doc) {
var event = Array();
$.each(doc, function(i, entry)
event.push({title: entry.title, start: entry.start});
});
$('#calendar').fullCalendar({
header: {
left: 'prev,next',
center: 'title',
right: 'month,agendaWeek,agendaDay'
},
defaultDate: '2014-06-12',
editable: true,
events: event
});
});

Related

Using AJAX response to fill JSON object

I'm using fullcalender.io which takes in a json array of objects. I'm using AJAX to call a php function, which succesfully returns a JSON object which i can see in the console. I just can't get it to full up the events object as it tells me events is not defined. I've tried initiating var events before but it doesnt the variable isnt defined.
$('#calendar').fullCalendar({
events: [
//Here needs to be filled
],
dayClick: function(date, jsEvent, view) {
var data = {
action: 'getCountOfReservationOnDate',
date: date.format() + " 00:00:00"
}
$.ajax({
type: 'POST',
url: "/modules/ajax/ajax_handler.php",
data: data
})
.done((result)=>{
if(result) {
console.log(data);
console.log(JSON.parse(result));
events.push(result); //From here
} else {
alert("Failed.")
console.log(result);
}
})
.fail(function($xhr) {
var data = $xhr.responseJSON;
//$("#validationError").text(data.message);
console.log(data.message);
})
.always(()=>{
//$('#loader').hide();
})
}
fullcalender.io provide some documentation related to ajax usage (events as a json feed). Consider the following script:
var calendar = new Calendar(calendarEl, {
events: '/modules/ajax/ajax_handler.php'
});
You might need to change your /modules/ajax/ajax_handler.php to provide the correct output. Since you did not post the code from it I'm not able to check it, but you probably find the answer on the linked document.
Your can try creating a variable where your ajax function can access it,
or create that variable globally at the topmost line in your file
tempEvent
$('#calendar').fullCalendar({
events: [
//Your can for loop the tempEvent to fill here
],
dayClick: function(date, jsEvent, view) {
var tempEvent = []
var data = {
action: 'getCountOfReservationOnDate',
date: date.format() + " 00:00:00"
}
$.ajax({
type: 'POST',
url: "/modules/ajax/ajax_handler.php",
data: data
})
.done((result)=>{
if(result) {
console.log(data);
console.log(JSON.parse(result));
tempEvent.push(result); //From here
} else {
alert("Failed.")
console.log(result);
}
})
.fail(function($xhr) {
var data = $xhr.responseJSON;
//$("#validationError").text(data.message);
console.log(data.message);
})
.always(()=>{
//$('#loader').hide();
})
}

can i put schedule in fullcalendar as ajax?

I want to add the ability to schedule in fullcalendar, Laravel. The method is working as expected however, I do not understand what to do with the response data.
$('#calendar').fullCalendar({
header: {
left : 'today, prev,next',
center: 'title',
right : '',
},
locale:'ko',
height:'parent',
events : function(start, end, timezone, callback){
var month = $('#calendar').fullCalendar('getDate').format('YYYY-MM');
var url = '{{route('reservation.get_schedule',[request()->id])}}';
alert(url)
$.ajax({
type : 'get',
data : {'date' : month},
url : url,
datatype : 'json',
success : function(data){
console.log(data); // How do I use the data
}
});
}
});
The documentation for events-as-a-function says:
[The function]... will also be given callback, a function that must be called when
the custom event function has generated its events. It is the event
function’s responsibility to make sure callback is being called with
an array of Event Objects.
There's also an example on that page where the callback function is employed to pass the event data returned from the AJAX call into fullCalendar.
So in your case (assuming that your event data is already in the format required by fullCalendar and doesn't need any transformation) you would simply add a call to this function inside your "success" callback:
events : function(start, end, timezone, callback){
var month = $('#calendar').fullCalendar('getDate').format('YYYY-MM');
var url = '{{route('reservation.get_schedule',[request()->id])}}';
alert(url)
$.ajax({
type : 'get',
data : {'date' : month},
url : url,
datatype : 'json',
success : function(data){
console.log(data);
callback(data); //pass the event data to fullCalendar via the provided callback function
}
});
}
$('#calendar').fullCalendar({
events: function(start, end, timezone, callback) {
$.ajax({
url: 'myxmlfeed.php',
dataType: 'xml',
data: {
// our hypothetical feed requires UNIX timestamps
start: start.unix(),
end: end.unix()
},
success: function(doc) {
var events = [];
$(doc).find('event').each(function() {
events.push({
title: $(this).attr('title'),
start: $(this).attr('start') // will be parsed
});
});
callback(events);
}
});
}
});
DOC

unable to create dynamic events in fullcalendar

i have a situation in which i m trying to create events dynamically using the plugin fullcalendar im trying to create events with the help of the ajax call and the data retrieved is in the form of json
when i m trying to create events only event at index 0 is getting created rest of events are not created
the javascript code is as follows
function showData()
{
var ids = showValidData();
if (ids.length != 0)
{
$.ajax({
url: $("#base-url").val() ,
type: 'POST',
data: {'ids': ids},
dataType: 'json',
success: function (response)
{
var data = response.data;
var myevents = [];
if (response.success)
{
$(data).each(function (index, value) {
myevents.push({
title: value.layoutName,
start: value.startDate,
end: value.endDate
});
});
console.log(myevents);
$(".fc-event-container").click();
$('#calendar-example-1').fullCalendar({
events: myevents,});
return;
}
}
});
}
}
Set events when initializing FullCalendar - define the url of the script that returns a json of events from your database (https://fullcalendar.io/docs/event_data/events_function/). If you want to dynamically refresh the calendar , you can add a setInterval ontop:
$(document).ready(function(){
setInterval(function(){$('#calendar').fullCalendar('refetchEvents')}, 30000);
$("#calendar").fullCalendar({
...
events: {
url: 'script.php',
type: 'POST',
data: {
data1: x,
data2: y
},
success : function(response){
// do something
},
}
});
});

Issue in displaying events in Fullcalendar.js

Hi I am trying to implement FullCalendar.js with Asp.Net MVC. I am abl to show empty calendar but my events are not getting loaded in the Calendar.
$.ajax({
type: 'Get',
url: "/Matter/GetMatterEventsSummary",
data: data,
datatype: "Json",
contentType: "application/json",
success: function (doc) {
debugger;
$('#calendar').fullCalendar();
var events = [];
$(doc).find('[object Object],[object Object]').each(function () {
debugger;
events.push({
title: $(this).attr('title'),
start: $(this).attr('start') // will be parsed
});
// });
$('#calendar').fullCalendar('refetchEvents');
// callback(events);
}
});
it comes to success method and it has two events in it . but dont know why theseevents are not loaded into FullCalendar and also after this Calendar is not comingg automatically.
I guess it is not going in events.push. When I do hover on doc it shows "[object Object],[object Object]" and in this it has two records on [0] and [1].
Please help me in this.
Try using
$('#calendar').fullCalendar( 'rerenderEvents' )
after your events have been pulled.
Also, make sure to use the code from the official documentation properly. Try the following (untested):
$('#calendar').fullCalendar({
events: function(start, end, timezone, callback) {
$.ajax({
type: 'Get',
url: "/Matter/GetMatterEventsSummary",
data: data,
datatype: "Json",
contentType: "application/json",,
success: function(doc) {
var events = [];
$(doc).find('event').each(function() {
events.push({
title: $(this).attr('title'),
start: $(this).attr('start') // will be parsed
});
});
callback(events);
}
});
}
});
If you now want to refetch your events, call :
$('#calendar').fullCalendar('refetchEvents');
where necessary.
EDIT:
Since your are actually pulling data from a JSON feed, the following code may even be enough:
$('#calendar').fullCalendar({
events: '/Matter/GetMatterEventsSummary'
});
Check the documentation here:
EDIT2:
To dynamically modify the request you send to the backend (depending on a dropdown or something else), may be achieved as follows:
var myValue = 10;
$('#calendar').fullCalendar({
events: '/Matter/GetMatterEventsSummary',
data: function() { // a function that returns an object
return {
dynamic_value: myValue
};
}
});

fullCalendar custom events function throws not a function error

im feeding the calendar with the following function:
$('#calendar').fullCalendar( {
header: {
left: 'prev,next today',
center: 'title',
right: 'month,agendaWeek,agendaDay' },
editable: true,
eventLimit: true,
events: function(callback) {
$.ajax({
url: '/appointments.json',
dataType: 'json',
success: function(doc) {
var events = [];
$(doc).find('event').each(function() {
events.push({
title: $(this).attr('title'),
start: $(this).attr('start') // will be parsed
});
});
callback(events);
}
});
But i keep getting this error:
object is not a function //callback(events) line
On the js console of the browser. Any idea what the problem might be?
Assuming you are using FullCalendar 2.*, as stated in the documentation, the signature for events is
function( start, end, timezone, callback ) { }
The parameter with the name callback is, in fact, start which is a momentjs object. To resolve your issue you must add the parameters to your function, so your code would be:
events: function( start, end, timezone, callback ) {
This will work as long as your events (passed to the callback) have the correct format and parameters defined in the documentation.
Edit:
If you want to set background color of each event according to a value on its json attributes, you should use eventRender.
Check this jsfiddle where the background of each event is set when the event is rendering.
As is demonstrated in the jsfiddle, you can change the background, conditionally, based on a value provided by the json.

Categories