FullCalendar not rendering all events through AJAX/JSON - javascript

I've been messing around with FullCalendar for a while now, but I have a slight issue. If I load events through AJAX/JSON in the correct format the calendar only renders the first event.
All other events are showing in the console.log call, but the calendar only shows the first one. The sample events code from documentation is as follows:
events: [{
title: 'My Event',
start: '2010-01-01',
url: 'http://google.com/'
},
{
title: 'My Event',
start: '2010-01-02',
url: 'http://google.com/'
}
// other events here
],
My code is below:
events: function(start, end, timezone, callback) {
function csrfSafeMethod(method) {
// these HTTP methods do not require CSRF protection
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
$.ajaxSetup({
beforeSend: function(xhr, settings) {
if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
}
});
$.ajax({
url: "/tande/fetch_holidays/",
type: 'POST',
success: function(data) {
var events = [];
$.map(data.holidays, function(value) {
console.log(value)
description = value.toString().split('_')[0]
start_date = value.toString().split('_')[1]
end_date = value.toString().split('_')[2]
person = value.toString().split('_')[3]
events.push({
title: person,
start: start_date,
end: end_date
});
callback(events);
console.log(events);
})
},
})
},

The callback to events was placed too early. Correct code below:
events: function(start, end, timezone, callback) {
function csrfSafeMethod(method) {
// these HTTP methods do not require CSRF protection
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
$.ajaxSetup({
beforeSend: function(xhr, settings) {
if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
}
});
$.ajax({
url: "/tande/fetch_holidays/",
type: 'POST',
success: function(data) {
var events = [];
$.map(data.holidays, function(value) {
console.log(value)
description = value.toString().split('_')[0]
start_date = value.toString().split('_')[1]
end_date = value.toString().split('_')[2]
person = value.toString().split('_')[3]
events.push({
title: person + ' - ' + description,
start: start_date,
end: end_date,
});
})
callback(events);
},
})
},

Related

editEvent reload page even if nothing change

When I click on an event in my calendar (made with fullcalendar3) it apparead a modal where I can change name, start and end of the event.
When I close this modal it reload the page, no matter if i change something or not.
Is there a way to stop the page from reload if I dont make changes?
This is my function to edit events in JS:
eventClick: function eventClick(event) {
$('#editNewEvent').modal('show').one('hidden.bs.modal', function (e) {
event.title = $('#editEname').val();
event.start = $('#editStarts').val();
event.end = $('#editEnds').val();
event.descrizione = $('#editDescrizione').val();
$.ajax({
url: 'eventi/updateEvent.php',
type: 'POST',
data: {start: event.start, _id: event.idAssenza, end: event.end, title: event.title, descrizione: event.descrizione},
success: function() {
location.reload();
}
});
$('#calendar').fullCalendar('updateEvent', event._id);
});
}
I found online this kind of solution:
success: function(data) {
var result = data;
location.reload();
}
});
return result;
But it doesnt change anything, still reload the page even if I dont modify anything
From an other question of mine I had this solution:
eventClick: function eventClick(event) {
$('#editNewEvent').modal('show');
//*salva* is the ID of my button
$("#salva").click(function() {
event.title = $('#editEname').val();
event.start = $('#editStarts').val();
event.end = $('#editEnds').val();
event.descrizione = $('#editDescrizione').val();
$.ajax({
url: 'eventi/updateEvent.php',
type: 'POST',
data: {start: event.start, _id: event.idAssenza, end: event.end, title: event.title, descrizione: event.descrizione},
success: function() {
location.reload();
}
});
$('#calendar').fullCalendar('updateEvent', event._id);
});
}

Fullcalendar not rendering events

I have this code that creates an array of event objects, which is then passed into the calendar, but for some reason the calendar does not render the events.
$(document).ready(function() {
$('#calendar').fullCalendar({
header: {
left: 'title',
center: '',
right: 'prev,next'
},
editable: true,
eventLimit: true,
events: function(start, end, timezone, callback) {
$.ajax({
success: function(doc) {
var events = [];
$.getJSON('../php/logg.php', function(data) {
$.each(data, function(key, val){
var temp = moment($(this).attr('dato'))
if(temp.isBefore(start)){ return true; }
else if(temp.isAfter(end)){ return true; }
else{x
events.push({
id: $(this).attr('id'),
title: $(this).attr('artist'),
start: $(this).attr('dato'),
allDay: false
});
}
}
);
});
var ektearray = $.makeArray(events);
callback(events);
}
});
}
});
});
When I output events to the console I get an array of objects, which seem to be working as expected. The objects are in the form:
allDay:false
id:"66"
start:"2016-11-04"
title:"Galantis"
__proto__:Object
It seems like I am either messing up the callback, or that my events are missing something, but I can't seem to figure out what
If I understand correctly, you want to execute the function(doc) upon success of the ajax call. If so, your syntax seems no to be properly written.
$.ajax({
method: "POST",
url: "some.php",
data: { name: "John", location: "Boston" }
})
.success(function() {
alert( "success" );
});

Recurring events in FullCalendar with Laravel

I'm working on a fullcalendar module for my page.I could display Events on calendar without the recurring feature. But when I altered my table to include recurring features I could not display events from the table.
This is my table structure.
The Update function in controller is called while the form is submitted and i noticed that it is being updated in the table.This is my form.
and this is my controller update function.
public function update($id)
{
//$type=Input::get('type');
$event_id= Input::get('eventid');
$title= Input::get('title');
$start_day=Input::get('start');
$end_day=Input::get('end');
$allday=Input::get('allday');
$repeat=Input::get('repeat');
$frequency=Input::get('frequency');
$start_time=Input::get('start_time');
$end_time=Input::get('end_time');
$dow=Input::get('dow');
$month=Input::get('month');
$weekly_json=json_encode($dow);
$monthly_json=json_encode($month);
$newstrt=substr($start_day,0,10);
$newend=substr($end_day,0,10);
$start= date("Y-m-d H:i:s",$newstrt);
$end= date("Y-m-d H:i:s" , $newend);
$roles = DB::table('events')
->where('event_id','=',$event_id)
->update(array('title' => $title,'daily'=>$allday,'repeat'=>$repeat,'frequency'=>$frequency,'start'=>$start,'end'=>$end,'time'=>$time,'dow'=>$weekly_json,'monthly_json'=>$monthly_json));
if (Request::ajax())
{
return Response::json(array('id'=>$event_id,'title'=>$title,'newstrt'=>$start,'newend'=>$end,'start_time'=>$start_time,'end_time'=>$end_time));
}
else
{
return Redirect::route('calendar.index');
}
}
But I'm not being able to display these details on the full calendar.I was following this link to implement recurring events on fullcalendar.
Recurring Events in FullCalendar.
This is my index function used for GETting details from the table.
public function index()
{
$event = DB::table('events')
->leftJoin('people','people.people_id','=','events.people_id')
->where('events.flag', '=', 1)
->get(array('events.event_id','events.title','events.start','events.end','events.start_time','events.end_time','events.repeat','events.frequency','events.dow'));
$id=array(array());
$temp = array(array());
$i=0;
foreach ($event as $events)
{
$j=0;
$id[$i]["event_id"]=$events->event_id;
$id[$i]["title"]=$events->title;
$temp[$j]['start']=$events->start;
$temp[$j]['end'] = $events->end;
$temp[$j]['start_time']=$events->start_time;
$temp[$j]['end_time'] = $events->end_time;
$start_json=json_encode($temp);
$id[$i]['range'] = $start_json;
$id[$i]["frequency"]=$events->frequency;
$id[$i]["repeat"]=$events->repeat;
$id[$i]["dow"]=$events->dow;
$i++;
}
return Response::json($id);
}
This is my calendar eventrender function and events structure.
var date = new Date();
var d = date.getDate();
var m = date.getMonth();
var y = date.getFullYear();
var repeatingEvents = [{
url: '/v1/calendar/',
type: 'GET',
ranges: [{ //repeating events are only displayed if they are within one of the following ranges.
start: moment().startOf('week'), //next two weeks
end: moment().endOf('week').add(7,'d'),
},{
start: moment('2015-02-01','YYYY-MM-DD'), //all of february
end: moment('2015-02-01','YYYY-MM-DD').endOf('month'),
}],
}];
console.log(repeatingEvents);
var getEvents = function( start, end ){
return repeatingEvents;
}
var calendar=$('#calendar');
$.ajax({
url: '/v1/calendar/',
type: 'GET',
dataType:'json',
success:function events(response)
{
console.log(response);
calendar.fullCalendar({
header: {
left: 'prev,next today',
center: 'title',
right: 'month,agendaWeek,agendaDay'
},
eventRender: function(event, element, view){
console.log(event.start.format());
return (event.range.filter(function(range){
return (event.start.isBefore(range.end) &&
event.end.isAfter(range.start));
}).length)>0;
},
events: function( start, end, timezone, callback ){
var events = getEvents(start,end); //this should be a JSON request
callback(events);
},
editable: true,
droppable: true, // this allows things to be dropped onto the calendar
drop: function() {
// is the "remove after drop" checkbox checked?
if ($('#drop-remove').is(':checked')) {
// if so, remove the element from the "Draggable Events" list
$(this).remove();
}
},
eventSources: [
{
url: '/v1/calendar/',
type: 'GET',
dataType:'json',
},
calendar.fullCalendar( 'addEventSource', response )
],
selectable: true,
selectHelper: true,
select: function(start, end, allDay)
and I am getting JSON response like this on the console.
dow: "{[0,1,2]↵}"
event_id: 1
frequency: "weekly"
range: "[{"start":"2015-09-11","end":"2015-09-12","start_time":"11:00:00","end_time":"15:00:00"}]"
repeat: 1
title: "Youth festival"
I get no errors on the console....but the events aren't displayed too..
where did i go wrong? Helps guys?
See this code, i am also facing
After that I use this idea ,its working
In Controller
$vendor_holiday = Vendor::all();
return view('vendorpanel/holidays/index', compact('vendor_holiday'));
<script>
var calendar = $('#calendar').fullCalendar({
editable: false,
header: {
left: 'prev,next today',
center: 'title',
right: 'month'
},
events: [
#foreach($vendor_holiday as $vendor_holiday)
{
title : "",
start : '{{ $vendor_holiday->start }}',
},
#endforeach
],
selectable: true,
selectHelper: true,
select: function (start, end, allDay) {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
var start = moment(start).format('YYYY-MM-DD');
var end = moment(end).format('YYYY-MM-DD');
var vendor_id = $("#vendor_id").val();
var tdate = new Date();
var dd = tdate.getDate(); //yields day
var MM = tdate.getMonth(); //yields month
var yyyy = tdate.getFullYear(); //yields year
var currentDate= yyyy+ "-" +0+( MM+1) + "-" + dd;
if(start <= currentDate){
alert("Mark Holiday at least 1 day before");
return false;
}
if (confirm("Are you sure you want to Add a Holiday?")) {
$.ajax({
url: "/vendor/holidays",
type: "POST",
data: { vendor_id: vendor_id, start: start, end: end },
success: function (d) {
calendar.fullCalendar('refetchEvents');
alert(d);
location.reload();
},
})
}
},
eventClick: function (calEvent, jsEvent, view, event) {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
if (confirm("Are you sure you want to remove it?")) {
var start = calEvent.start.format();
var vendor_id = $("#vendor_id").val();
$.ajax({
url: '/vendor/holidays/'+vendor_id,
type: "DELETE",
data: { _method: 'delete', start: start },
success: function (d) {
$('#calendar').fullCalendar('removeEvents', calEvent._id);
alert(d);
},
error: function (data) {
alert(data);
}
});
}
},
});
</script>
Laravel - Recurring event occurrences generator and organiser.
Calendarful is a simple and easily extendable PHP solution that allows the generation of occurrences of recurrent events, thus eliminating the need to store hundreds or maybe thousands of occurrences in a database or other methods of storage.
This package ships with default implementations of interfaces for use out of the box although it is very simple to provide your own implementations if needs be.
It is compliant with PSR-2.
Installation
This package can be installed via Composer:
https://github.com/Vij4yk/calendarful
$ composer require plummer/calendarful
It requires PHP >= 5.3.0
Try this package.

Update Fullcalendar event after creation?

When I create a new event, i POST it on the server with a tastypie REST API. When created, this event on the server has a new id, generated when is saved:
select: function (startDate, endDate, allDay, jsEvent, view) {
/* after selection user will be promted for enter title for event.*/
var title = prompt('Event Title:');
/*if title is enterd calendar will add title and event into fullCalendar. */
}
if (title) {
calendar.fullCalendar('renderEvent', {
title: title,
start: startDate,
end: endDate,
allDay: allDay
},
true // make the event "stick"
);
$.ajax({
url: 'http://localhost:8000/calendar/api/events/events/',
dataType: 'json',
contentType: 'application/json; encode=UTF-8',
type: 'POST',
data: JSON.stringify({
title: title,
start: startDate,
end: endDate,
allDay: allDay,
user: "/calendar/api/events/users/{{ user.id }}/"
}),
success: function (data) {
// Could i do something here?
}
});
console.log({{user.id}},'{{ user}}')
}
},
I need to update the event on the client memory, because the event just created, has an event id like "fc_1" or something similar, but i need the DB id, because if i immediately drag o resize the event, i can't update it on server because it will try to PUT this event, but with the wrong id (like "fc_1").
in your renderEvent object, you could add id: 'pending'. Then in your success function you can use the fullcalendar clientEvents function to get the array of events and then use updateEvent to add your new id value:
success: function(data) {
var newID = data.id;
var events = calendar.fullCalendar('clientEvents');
for(var i = 0; i < events.length; i++){
if(events[i].id == 'pending') {
events[i].id = newID;
calendar.fullCalendar('updateEvent', events[i]);
}
}
}

Jquery $.map function giving error

I have the following code to map events to FullCalendar
events: function(start, end, callback)
{
$.ajax(
{
type: 'POST',
dataType: 'json',
url: "Calendar.aspx/GetEvents",
contentType: 'application/json; charset=utf-8',
cache: false,
success: function (response) {
var events = [];
$.map(response.d, function (item) {
var event = new Object();
event.id = item.EventID;
event.start = new Date(item.StartDate);
event.end = new Date(item.EndDate);
event.title = item.EventName;
return event;
events.push(event);
})
callback(events);
},
error: function (err) {
alert('Error');
}
});
},
The Calendar.aspx/GetEvents function returns the following data successfully:
"[{"EventID":1,"EventName":"EventName 1","StartDate":"04-04-2014","EndDate":"04-06-2014"},{"EventID":2,"EventName":"EventName 2","StartDate":"04-08-2014","EndDate":"04-09-2014"},{"EventID":3,"EventName":"EventName 3","StartDate":"04-14-2014","EndDate":"04-15-2014"},{"EventID":4,"EventName":"EventName 4","StartDate":"04-26-2014","EndDate":"04-29-2014"}]"
I want to iterate through this data and assign it to the calendar.
My above $map function gives me the following error:
Cannot use in operator to search for 352 in [{"EventID":1,"EventName":"EventName 1","StartDate":"04-04-2014","EndDate
How can I do this??
You're using $.map incorrectly. The point of it is that it creates an Array, so there's no need to create one before the loop and .push() into it.
You should keep the return statement, remove the .push, and set the return value of $.map to the events variable.
success: function (response) {
var events = $.map(response.d, function (item) {
var event = new Object();
event.id = item.EventID;
event.start = new Date(item.StartDate);
event.end = new Date(item.EndDate);
event.title = item.EventName;
return event;
});
callback(events);
},
However, object literal syntax is nicer.
success: function (response) {
var events = $.map(response.d, function (item) {
return {
id: item.EventID,
start: new Date(item.StartDate),
end: new Date(item.EndDate),
title: item.EventName,
};
});
callback(events);
},
The error message shown in your question doesn't seem to make sense for the code provided.

Categories

Resources