Fullcalendar: How to remove event - javascript

Thanks to another post here on StackOverflow, I added some code to my select: method that prevents users from adding an event on a date prior to NOW.
The downside is that when they click on the empty time slot, and the system then complains (an alert message), the attempted event remains. How do I get rid of it? Thanks!
Update: Here's my code:
select: function(start, end, jsEvent) {
var check = start._d.toJSON().slice(0,10),
today = new Date().toJSON().slice(0,10),
m = moment(),
url = "[redacted]",
result = {};
title = "Class",
eventData = {
title: title,
start: start,
end: start.clone().add(2, 'hour'),
durationEditable: false,
instructorid: 123,
locationid: 234
};
if(check < today) {
alert("Cannot create an event before today.");
$("#calendar").fullCalendar('removeEvents', function(eventObject) {
return true;
});
} else {
$.ajax({ type: "post", url: url, data: JSON.stringify(eventData), dataType: 'JSON', contentType: "application/json", success: function(result) {
if ( result.SUCCESS == true ) {
$('#calendar').fullCalendar('renderEvent', eventData, true);
$('#calendar').fullCalendar('unselect');
} else {
alert(result.MESSAGE);
}
}});
}
}

If you're using FullCalendar V2, you need to use the removeEvents method.
You can use it to delete events with a certain ID by calling it in this way:
$("#calendar").fullCalendar('removeEvents', 123); //replace 123 with reference to a real ID
If you want to use your own function that decides whether or not an event get's removed, you can call it this way:
$("#calendar").fullCalendar('removeEvents', function(eventObject) {
//return true if the event 'eventObject' needs to be removed, return false if it doesn't
});

FullCalendar has a removeEvent method that uses an id when you create the event.
Example Full Calendar v1:
var calendar = $('#calendar').fullCalendar({ ... stuff ... });
calendar.fullCalendar( 'addEventSource', {id:123, stuff:'stuff'});
// ... other calendar things here...
calendar.fullCalendar( 'removeEvent', 123);
Reference API v1
Example FullCalendar v2:
var calendar = $('#calendar').fullCalendar({ ... stuff ... });
calendar.fullCalendar( 'addEventSource', {id:123, stuff:'stuff'});
// ... other calendar things here...
calendar.fullCalendar( 'removeEvents', [123]);
Reference API v2

Version 4.3
calendar = new Calendar(calendarEl, {
plugins : [ 'interaction', 'dayGrid', 'list' ],
header : {
left : 'prev,next today',
center : 'title',
right : 'dayGridMonth,timeGridWeek,timeGridDay,list'
},
editable : true,
droppable : true,
eventReceive : function(info) {
alert(info.event.title);
},
eventDrop : function(info) {
alert(info.event.title + " was dropped on "
+ info.event.start.toISOString());
if (!confirm("Are you sure about this change?")) {
info.revert();
}
},
eventClick : function(info) {
//delete event from calender
info.event.remove();
}
});
calendar.render();
});

Full calendar version 4
How to remove event from calendar:
<div id="calendar"></div>
<script>
document.addEventListener('DOMContentLoaded', function() {
var calendarEl = document.getElementById('calendar');
var calendar = new Calendar(calendarEl, {
events: [
{
id: '505',
title: 'My Event',
start: '2010-01-01',
url: 'http://google.com/'
}
// other events here
],
eventClick: function(info) {
info.jsEvent.preventDefault(); // don't let the browser navigate
if (info.event.id) {
var event = calendar.getEventById(info.event.id);
event.remove();
}
}
});
});
</script>
This worked for me. I hope, this will also help you. Thanks for asking this question.

Related

google calendar sync with full calendar io

I have developed event entry with jquery and php in full-calendar io. Now I want to add google calendar sync with this. How can I do that? I have read the documentation. In the events parameter I have to add events:
{ googleCalendarId: 'abcd1234#group.calendar.google.com' }
but I already added a php file (load.php) parameter. How I can use both of them together?
$(document).ready(function() {
var calendar = $('#calendar').fullCalendar({
editable:true,
header:{
left:'prev,next today',
center:'title',
right:'month,agendaWeek,agendaDay'
},
events: 'load.php',
selectable:true,
selectHelper:true,
select: function(start, end, allDay)
{
var start = $.fullCalendar.formatDate(start, "Y-MM-DD");
var end = $.fullCalendar.formatDate(end, "Y-MM-DD");
$("#form1").toggle();
//alert(title);
$("#submit").click(function() {
var title = prompt("Enter Event Title");
if(title)
{
var tname="Rayhan";
var course=document.getElementById("course").value;
console.log(course);
var email="showrov#test.com";
var descrip=document.getElementById("descrip").value;
$.ajax({
url:"insert.php",
type:"POST",
data:{title:title, start:start, end:end, tname:tname, course:course,
email:email, descrip:descrip},
success:function()
{
calendar.fullCalendar('refetchEvents');
alert("Added Successfully");
}
});
}//
})
},
You can do it by using by using the Event Sources feature. This allows you to define more than one source of data for your calendar events.
Simply replace
events: 'load.php'
with
eventSources: [
'load.php',
{ googleCalendarId: 'abcd1234#group.calendar.google.com' }
]
Now your calendar will load events from both locations. It is documented here: https://fullcalendar.io/docs/eventSources.
You must also ensure that you carry out the other setup steps documented in https://fullcalendar.io/docs/google-calendar to get your Google Calendar feed working.

How to register an event using addEventSource in fullCalendar?

When I click on the dayClick, I want to add an event to the clicked date.
I have the following JS code:
$('#calendar').fullCalendar({
header: {
center: "title", // 센터에는 타이틀 명이 오고
left: "prev", // 왼쪽에는 < 버튼이 오고
right: "next" // 오른쪽에는 > 버튼이 오게됌
},
lang: 'ko', // 달력 한글 설정
editable: true, // 달력의 이벤트를 수정할 수 있는지 여부를 결정
dayClick: function(date, allDay, view) // 일 클릭시 발생
{
var dateFormat = date.format('YYYY-MM-DD');
if (confirm('Do you want to register as closed?')) {
// Register event
} else {
alert('You Click No');
}
}
});
//Register event this part, how do I add the code?
I've been very careful with the "select" feature, but the functionality I want to implement is simple, so I prefer using "addEventSource" rather than "select".
But I am a beginner of jquery and javascript, so I do not know how to write it.
Please guide me on how to write code.
And I would really appreciate it if you could give me a link to a site or question I could refer to.
(Oh, note that all title values for events to be registered are "closed")
Set the following options for fullcalendar. See select demo.
selectable: true,
selectHelper: true,
select: function (start, end, jsEvent, view) {
var title = 'Some Event';
var eventData = {
title: title,
start: start,
end: end
};
if (confirm('Do you want to register as closed?')) {
$('#calendar').fullCalendar('renderEvent', eventData, true); // stick? = true
} else {
alert('You Click No');
}
$('#calendar').fullCalendar('unselect');
},
Setting the select callback allows the use to click and drag to select multiple dates and set an event.
To allow only single day events, restrict the user to only clicks by setting dayClick option for fullcalendar instead.
dayClick: function (start, end, jsEvent, view) {
var title = 'Some Event';
var eventData = {
title: title,
start: start,
};
if (confirm('Do you want to register as closed?')) {
$('#calendar').fullCalendar('renderEvent', eventData, true); // stick? = true
} else {
alert('You Click No');
}
$('#calendar').fullCalendar('unselect');
},

How can i read events from my database table and show them in their respective dates in java script and jquery

i use Full calendar plugin to do this and i have done something but still did not get up to mark.
hear is my scripting code
$('#calendar').fullCalendar({
//theme: true,
header: {
left: 'prev,next today',
center: 'title',
right: 'month,agendaWeek,agendaDay'
},
buttonText: {//This is to add icons to the visible buttons
prev: "<span class='fa fa-caret-left'></span>",
next: "<span class='fa fa-caret-right'></span>",
today: 'today',
month: 'month',
week: 'week',
day: 'day'
},
editable: true,
droppable: true, // this allows things to be dropped onto the calendar
drop: function(date) { // this function is called when something is dropped
// retrieve the dropped element's stored Event Object
var originalEventObject = $(this).data('eventObject');
// we need to copy it, so that multiple events don't have a reference to the same object
var copiedEventObject = $.extend({}, originalEventObject);
// assign it the date that was reported
copiedEventObject.start = date;
copiedEventObject.backgroundColor = $(this).css("background-color");
copiedEventObject.borderColor = $(this).css("border-color");
console.log(copiedEventObject);
// render the event on the calendar
// the last `true` argument determines if the event "sticks" (http://arshaw.com/fullcalendar/docs/event_rendering/renderEvent/)
$('#calendar').fullCalendar('renderEvent', copiedEventObject, true);
// is the "remove after drop" checkbox checked?
/*alert(date + ' was moved ' + allDay + ' days\n' +
'(should probably update your database)');*/
},
//events:"web_master/mycal/ajax_fetch_calendar_data",
events: function(start, end, timezone, callback) {
$.ajax({
url: 'web_master/mycal/ajax_fetch_calendar_data',
dataType: 'json',
type: "POST",
success: function(doc) {
//console.log(doc);
var events = [];
$(doc).find('event').each(function(){
console.log(doc);
events.push({
title: $(this).attr('title'),
start: $(this).attr('start') // will be parsed
});
});
}
});
},
});
in this i successfully found my doc in events section.
here is the code to fetch events from DB
public function ajax_fetch_calendar_data()
{
try
{
$info = $this->mod_rect->fetch_calendar();
#pr($info);
for($i = 0 ; $i < count($info) ; $i++)
{
$rows[]= array("id"=>$info[$i]['i_id'],
"title"=> $info[$i]['s_title'],
"start"=> $info[$i]['dt_start_date'],
"end"=>$info[$i]['dt_end_date'],
"allDay"=> $info[$i]['s_allDay']);
}
if($rows)
{
echo json_encode($rows);
}
}
catch(Exception $err_obj)
{
show_error($err_obj->getMessage());
}
}
but there is an find(event) function which is didn't found.
Basically what i need to do that
i have some events, those are fetch from DB and i have to drag them on the specific date on the date that comes(upto this done), but i want to store that in Db and fetch them from DB.
I am new to java script and jquery and i didn't know about JSON also.
any help regarding this will helpfull to me.
Thanks.
Well
After few days I have done it myself.
And I think it would be help full to someone So i update my Question
In the Events Section of Fullcalendar for reading multiple events and showing them in your Fullcalendar
events: function(start, end, callback) {
$.ajax({
url: 'web_master/mycal/ajax_fetch_calendar_data',
dataType: 'json',
type: "POST",
success: function(doc) {
var eventObject = [];
for(i=0;i<doc.length;i++)
{
eventObject.push({
id : doc[i].id,
start : doc[i].start,
end : doc[i].end,
title : doc[i].title
//allDay : doc[i].allDay,
//backgroundColor : doc[i].backgroundColor,
//borderColor : doc[i].borderColor
});
}
callback(eventObject);
}
});
},
And i fetch it from my DB in this way
public function ajax_fetch_calendar_data()
{
try
{
$info = $this->mod_rect->fetch_calendar();
echo json_encode($info);
}
catch(Exception $err_obj)
{
show_error($err_obj->getMessage());
}
}

Fullcalendar - Can we add custom data to our event Json Data?

I want to send a type in my Event Json Response.
Here is my code:
$('#calendar').fullCalendar({
eventSources: [
{"id":"46_l","title":"CustomEvent-Chargement","start":"2013-12-02","end":"2013-12-03","className":"customEventsClass","type":1},
{"id":"46_d","title":"Custom Event-Livraison","start":"2013-12-11","end":"2013-12-12","className":"customEventsClass","type":2}
]
});
You see I send a type in JSON Response array, is this possible? What parameter can we use for sending our custom data?
As per the documentation:
Non-standard Fields
In addition to the fields above, you may also include your own non-standard fields in each Event Object. FullCalendar will not modify or delete these fields. For example, developers often include a description field for use in callbacks such as eventRender.
Example:
$('#calendar').fullCalendar({
events: [
{
title: 'My Event',
start: '2010-01-01',
type: 1 // Custom field
}
],
eventRender: function(event, element) {
console.log(event.type); // Writes "1"
}
});
Try It with events: instead of eventSources:
$('#calendar').fullCalendar({
events: [
{"id":"46_l","title":"CustomEvent-Chargement","start":"2013-12-02","end":"2013-12-03","className":"customEventsClass","type":1},
{"id":"46_d","title":"Custom Event-Livraison","start":"2013-12-11","end":"2013-12-12","className":"customEventsClass","type":2}
]
});
In the new version you should do this:
eventRender: function (info) {
info.el.firstChild.innerHTML = info.event.extendedProps.type + " " + info.event.extendedProps.customEventsClass;
}
In version 4 custom data is in extendedProps.
In short e.event.extendedProps
You can also pass url endpoint to events as long as the url returns json response
cId.fullCalendar({
header: {
right: '',
center: 'prev, title, next',
left: ''
},
theme: true, //Do not remove this as it ruin the design
selectable: true,
selectHelper: true,
editable: true,
//it will load data from this url
events: "{{ url('api/events') }}",
// events: getData(),
//Add Events
});
and in your controller or function
$events = $request->user()->events()->select('title','color','date')->get();
// dd($even,$events)
$eventsResponse = [];
// created_at->format('Y-m-d')
foreach ($events as $event)
{
$eventsResponse[] = [
'title'=>$event->title,
'color'=>$event->color,
'start'=> Carbon::parse($event->date)->toDateTimeString(),
];
}
return $eventsResponse;

Loading fullcalendar events from a backbone collection breaks the next & previous functions

noob coder here.
I'm having trouble linking fullcalendar to backbone.js. My problem arises when I use the 'previous' and 'next' buttons on fullcalendar to navigate.
Here is the bug: I make a new event. The event shows up on the calendar. I press 'next'. I press 'previous'. The new event has disappeared.
It looks like fullcalendar expects an 'events' option on loading to specify a function or JSON feed to load events from. According to the docs, "FullCalendar will visit the URL whenever it needs new event data. This happens when the user clicks prev/next or changes views."
I'm having a surprising amount of difficulty getting fullcalendar to ask Backbone for a JSON object of the events collection(that stores all the events).
I've tried using
events: function() {events.toJSON();}
and
events: function() {events.fetch();}
with no luck. Help is very much appreciated.
Here is my backbone code:
$(function(){
var Event = Backbone.Model.extend();
var Events = Backbone.Collection.extend({
model: Event,
url: 'events'
});
var EventsView = Backbone.View.extend({
initialize: function(){
_.bindAll(this);
this.collection.bind('reset', this.addAll);
this.collection.bind('add', this.addOne);
this.collection.bind('change', this.change);
this.collection.bind('destroy', this.destroy);
this.eventView = new EventView();
},
render: function() {
this.el.fullCalendar({
header: {
left: 'prev,next today',
center: 'title',
right: 'month,basicWeek,basicDay'
},
selectable: true,
selectHelper: true,
editable: true,
ignoreTimezone: false,
select: this.select,
defaultView: 'agendaWeek',
// events: function() {events.toJSON();},
eventClick: this.eventClick,
eventDrop: this.eventDropOrResize,
eventResize: this.eventDropOrResize
});
},
addAll: function() {
this.el.fullCalendar('addEventSource', this.collection.toJSON());
},
addOne: function(event) {
this.el.fullCalendar('renderEvent', event.toJSON());
},
select: function(startDate, endDate) {
this.eventView.collection = this.collection;
this.eventView.model = new Event({start: startDate, end: endDate});
this.eventView.render();
},
eventClick: function(fcEvent) {
this.eventView.model = this.collection.get(fcEvent.id);
this.eventView.render();
},
change: function(event) {
// Look up the underlying event in the calendar and update its details from the model
var fcEvent = this.el.fullCalendar('clientEvents', event.get('id'))[0];
fcEvent.title = event.get('title');
fcEvent.color = event.get('color');
this.el.fullCalendar('updateEvent', fcEvent);
},
eventDropOrResize: function(fcEvent) {
// Lookup the model that has the ID of the event and update its attributes
this.collection.get(fcEvent.id).save({start: fcEvent.start, end: fcEvent.end});
},
destroy: function(event) {
this.el.fullCalendar('removeEvents', event.id);
}
});
var EventView = Backbone.View.extend({
el: $('#eventDialog'),
initialize: function() {
_.bindAll(this);
},
render: function() {
var buttons = {'Ok': this.save};
if (!this.model.isNew()) {
_.extend(buttons, {'Delete': this.destroy});
}
_.extend(buttons, {'Cancel': this.close});
this.el.dialog({
modal: true,
title: (this.model.isNew() ? 'New' : 'Edit') + ' Event',
buttons: buttons,
open: this.open
});
return this;
},
open: function() {
this.$('#title').val(this.model.get('title'));
this.$('#color').val(this.model.get('color'));
},
save: function() {
this.model.set({'title': this.$('#title').val(), 'color': this.$('#color').val()});
if (this.model.isNew()) {
this.collection.create(this.model, {success: this.close});
} else {
this.model.save({}, {success: this.close});
}
},
close: function() {
this.el.dialog('close');
},
destroy: function() {
this.model.destroy({success: this.close});
}
});
var events = new Events();
new EventsView({el: $("#calendar"), collection: events}).render();
events.fetch();
});
After looking at this problem forever I realized that I was adding the appointment(model) to the collection and calling renderEvent() without the [,stick] flag equal to true. This made my appointments disappear when pressing the next/back button.
http://arshaw.com/fullcalendar/docs/event_rendering/renderEvent/
From the documentation: "http://arshaw.com/fullcalendar/docs/event_rendering/renderEvent/"
"Normally, the event will disappear once the calendar refetches its event sources (example: when prev/next is clicked). However, specifying stick as true will cause the event to be permanently fixed to the calendar."

Categories

Resources