Fullcalendar filtrering events with select - javascript

I want to filter events by changing a select option, but I'm not sure how. Some help please(I want to clarify that this is the first time I use Json and FullCalendar)
Example:
Controller cCalendar
public function geteventos(){
$rut_usu = $this->input->post('rut_usu');
$r = $this->mCalendar->geteventos($rut_usu);
echo json_encode($r);
}
Model mCalendar
public function geteventos($rut_usu){
$this->db->select('CONCAT(estudiantes.pnombre," ", estudiantes.apellido_pa," ", estudiantes.apellido_ma,", ",motivos_citas.descripcion_mot) As title ,citas.id_ci id, citas.fecha_ini start, citas.fecha_ter end');
$this->db->from('citas');
$this->db->join('estudiantes', 'citas.rut_estu = estudiantes.rut_estu');
$this->db->join('motivos_citas','citas.id_mot = motivos_citas.id_mot');
$this->db->join('usuarios','citas.rut_usu = usuarios.rut_usu');
$this->db->where('usuarios.rut_usu',$rut_usu);
return $this->db->get()->result();
}
Javascript
$("#rut_usu").change(function(){
rut_usu = $('#rut_usu').val();
$.post('<?php echo base_url();?>cCalendar/geteventos',
$('#calendar').fullCalendar({
header: {
left: 'prev,next today',
center: 'title',
right: 'month,agendaWeek,agendaDay,listMonth'
},
defaultDate: new Date(),
navLinks: true, // can click day/week names to navigate views
businessHours: true, // display business hours
editable: true,
events: $.parseJSON(data)
});
}));

Your controller and modal is not any changes.
Only changes in js:
Create new javascript function:
function getEvents(rut_usu)
{
$('#calendar').fullCalendar( 'removeEvents');
$.ajax({
type:"GET",
url: "<?=base_url();?>cCalendar/geteventos",
dataType: 'json',
data: {rut_usu:rut_usu },
success: function(data){
$.each(data, function(index, event){
$('#calendar').fullCalendar('renderEvent', event);
});
}
});
}
Call this function into on change dropdown event:
<select id="rut_usu" OnChange="getEvents(this.value);">
-----
</select>
Render Event when change select option.

Related

fullCalendar: Getting data from controller JSON

I am using the fullCalendar library in Visual Studio 2015. I am having trouble populating events from an AJAX command. No events are populating on the calendar. If I pass only one datetime and set allDay = true, it will populate the event. I need it to work with time as well and ave multiple events per day.
JS Code:
$(document).ready(function () {
$(".calendar").fullCalendar
({
header: {
left: 'month,basicWeek,basicDay,today',
center: 'title',
right: 'prev,next'
},
weekends: false,
eventLimit: true,
theme: true,
editable: false,
fixedWeekCount: false,
events: function(start, end, timezone, callback)
{$.ajax
({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "/Calendar/GetCalendarEvents",
dataType: 'json',
success: function (data)
{
var events = [];
$.each(data, function (index, value) {
events.push({
id: value['id'],
title: value['title'],
date: value['date']
//all data
});
console.log(value)
});
callback(events);
},
error: function (xhr, err) {
alert("ERROR! - readyState: " + xhr.readyState + "<br/>status: " + xhr.status + "<br/>responseText: " + xhr.responseText);
}
});
} });})
Note: The above code was one of may attempts to get it working. I have tried coding it differently before.
Controller Code:
public ActionResult GetCalendarEvents()
{
var events = new List<VMCalendarEvents>();
var db_events = db.PatientVisits.ToList();
foreach(var e in db_events)
{
DateTime visit_start = Convert.ToDateTime(e.VisitStart);
DateTime visit_end = Convert.ToDateTime(e.VisitEnd);
var calEvent = new VMCalendarEvents
{
id = e.PatientVisitID.ToString(),
title = "Placeholder Title" + e.PatientVisitID.ToString(),
date = visit_start.ToShortDateString(),
start = visit_start.ToString(),
end = visit_end.ToString(),
editable = true,
allDay = false
};
events.Add(calEvent);
}
var rows = events.ToArray();
return Json(rows, JsonRequestBehavior.AllowGet);}
Controller Code Output
JS Objects from Controller
EDIT: Problem Solved
So after some investigating I decided to use Razor in MVC to solve the problem. Instead of writing it into a seperate JS file, I put it into a header in the html file. By implementing the code below I was able to get the objects in the date formats of (yyyy-MM-ddTHH:dd & MM/dd/yyyy hh:mm tt):
$(function () {
$('#calendar').fullCalendar({
header: {
left: 'prev,next today',
center: 'title',
right: 'month,agendaWeek,agendaDay'
},
defaultDate: '2017-06-12',
editable: true,
events: '#Url.Action("GetCalendarEvents", "Calendar")',
});
});
I called the Controller using the URL Action command and return the JSON data as a ActionResult.
Fullcalendar might not like your slashes '/' in your date fields. Try hyphens '-' instead.
The documentation (https://fullcalendar.io/docs/utilities/Moment/) is more detailed about what formats for date/time work.
For reference, here is my fullcalendar code using JSON from AJAX (note that my events do not have an end time, but this was by choice):
{
$.ajax({
url: 'example.json',
dataType: 'json',
success: function(doc) {
var events = [];
$.each(doc, function(index, element) {
events.push({
title: element.title,
start: element.time,
url: element.url,
});
});
callback(events);
}
}) //ajax
}
And the JSON file (example.json):
[
{"time": "2017-06-06 09:00:00", "title": "Get It Done in June ", "url": "http://example.org"},
{"time": "2017-06-07 14:00:00", "title": "Fighting Imposter Syndrome for Dissertating Students ", "url": "http://example.com"},
{"time": "2017-06-14 14:00:00", "title": "Entering into the Academic Conversation", "url": "http://example.biz"}
]

FullCalendar Show different information on dayClick

I have a calendar that shows different information on the month view and day view. I'd like to be able to allow the user to click into a day, then have the day show the specifics of each event. This is what I currently have below.
$('#calendar').fullCalendar({
// put your options and callbacks here
height: 750,
header: {
left: 'prev,next today ',
center: 'title',
right: 'month'
},
dayClick: function(date, jsEvent, view) {
},
displayEventTime: false,
events: function(start, end, timezone, callback) {
$.ajax({
type: 'POST',
url: 'WebServices/CalendarAtAGlanceWebService.asmx/GetCalendarSessions',
data: JSON.stringify({ date: $('#calendar').fullCalendar('getDate') }),
async: true,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (doc) {
var events = [];
$(doc.d).each(function () {
events.push({
title: $(this).attr('EventName'),
start: $(this).attr('StartDate'), // will be parsed
description: $(this).attr("EventDescription")
});
});
callback(events);
}
});
},
eventRender: function (event, element) {
element.find('.fc-title').append("<br/>" + event.description);
}
});
Full Calendar This is what the image looks like on the month view.
Make your dayClick function the following:
dayClick: function(date, jsEvent, view)
{
$('#calendar').fullCalendar('gotoDate', date);
$('#calendar').fullCalendar('changeView', agendaDay);
}
This will change the view to the day view of the clicked date when the user clicks on a day in month view. Then you just need to change your eventRender
logic to only display the description when in day view:
eventRender: function (event, element)
{
if($('#calendar').fullCalendar('getView').name == "agendaDay")
{
element.find('.fc-title').append("<br/>" + event.description);
}
}
This will make the description only appear for the events in day view. This means that you will see titles only in month view, and clicking on a day will show a view of the day's events with more detail.

How to pass a dynamic route to AJAX POST request in Rails

In my Rails app I am using the FullCalendar Rails gem and attempting to create user "bookings" with jQuery/AJAX. I currently am handling the fullcalendar javascript in a script tag on my profile show page as I wasn't sure how to access a dynamic route outside an erb file. Unfortunately my AJAX doesn't seem to be working at all. The select function still behaves as it should but nothing seems to be happening with the AJAX as I don't get a success or failure message and nothing is showing up in my network tab. I'm guessing I don't have the url route set up correctly and I also assume my general set up of the AJAX may be incorrect. UPDATE: I actually am getting a console error now when I submit an event showing up in the fullcalendar javascript file itself: 'Uncaught TypeError: Cannot read property '_calendar' of undefined’. I'm not really sure where that is coming from and there is still nothing showing up in my network tab from the ajax request.
<script>
$(document).ready(function() {
$('#calendar').fullCalendar({
header: {
left: 'prev,next today',
center: 'title',
right: 'month,agendaWeek,agendaDay'
},
defaultDate: '2016-01-12',
selectable: true,
selectHelper: true,
select: function(start, end) {
var title = "Unavailable";
var eventData;
eventData = {
title: title,
start: start,
end: end,
color: 'grey'
};
$('#calendar').fullCalendar('renderEvent', eventData, true); // stick? = true
$('#calendar').fullCalendar('unselect');
$.ajax({
method: "POST",
data: {start_time: start, end_time: end, first_name: title, color: 'grey'},
url: "<%= profile_bookings_url(#profile) %>",
success: function(data){
console.log(data);
},
error: function(data){
alert("something went wrong, refersh and try again")
}
})
},
editable: true,
eventLimit: true, // allow "more" link when too many events
events: window.location.href + '.json'
});
});
The select function above adds an event to the calendar with jQuery. What I would like to have happen with my AJAX is to submit that event to my bookings create action in my bookings controller.
def create
#profile = Profile.friendly.find(params[:profile_id])
#booking = #profile.bookings.new(booking_params)
if #booking.save
flash[:notice] = "Sending your booking request now."
#booking.notify_host
redirect_to profile_booking_path(#profile, #booking)
else
flash[:alert] = "See Errors Below"
render "/profiles/show"
end
end
Can anyone help me fix that AJAX call? I haven't really worked with it before so any help would be greatly appreciated! If there's any other info/code I should post, please let me know.
I ended up solving the issue. It had to do with the the format of my data: element of my ajax call. The working code:
<script>
$(document).ready(function() {
$('#calendar').fullCalendar({
header: {
left: 'prev,next today',
center: 'title',
right: 'month,agendaWeek,agendaDay'
},
defaultDate: '2016-01-12',
selectable: true,
selectHelper: true,
select: function(start, end) {
var title = "Unavailable";
var eventData;
eventData = {
title: title,
start: start,
end: end,
color: 'grey'
};
$.ajax({
method: "POST",
data: {booking:{start_time: start._d, end_time: end._d, first_name: title}},
url: "<%= profile_bookings_path(#profile, #booking) %>",
success: function(data){
console.log(data);
$('#calendar').fullCalendar('renderEvent', eventData, true); // stick? = true
$('#calendar').fullCalendar('unselect');
},
error: function(data){
alert("something went wrong, refersh and try again")
}
});
},
editable: true,
eventLimit: true, // allow "more" link when too many events
events: window.location.href + '.json'
});
});
It had to be wrapped with a booking object and my start and end times we moment.js objects so I had to access the actual start and end time from there. I'm still interested in areas to improve the code if need be, but at least it's working.
I can see some errors in your code.
change this:
url: "{<%= profile_bookings_url(#profile) %>}"
by this:
url: "<%= profile_bookings_url(#profile) %>"

fullcalendar js: fetching more events with ajax

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

Fullcalendar editable property not working?

Here is my code
$(document).ready(function() {
$('#calendar').fullCalendar({
header: {
left: 'prev,next today',
center: 'title',
right: 'month,basicWeek,basicDay'
},
dayClick: function() {
alert('nemke');
},
events: function(start, end, callback) {
$.ajax({
url: 'UserCalendarService.asmx/GetEvents',
type: 'POST',
dataType: 'xml',
data: {start: + Math.round(start.getTime() / 1000),end: + Math.round(end.getTime() / 1000)},
success: function(result) {
var events = [];
$(result).find('Event').each(function() {
events.push({
title: $(this).find('Title').text(),
start: $(this).find('Start').text(),
editable: $(this).find('Editable').text()
});
});
callback(events);
}
});
},
disableResizing: true,
editable: false
//disableDragging:true
})
});
This property editable false is not working. I tried to set each event it's behavior from the server, and it didn't work. Then I tried to set the property to false, and it also didn't work. I need to set some events editable and some not. I can only set disableDragging, but that doesn't solve my issue 'cause I need some of the events to be able to drag.
This property only works with event source set as array like this example
Looks like this ajax callback is not working. Has anyone had similar issue?
Fullcalendar link
the .text() method returns a string and editable is supposed to have a boolean value

Categories