i have the following data
then i want to display in full calendar
<script>
document.addEventListener('DOMContentLoaded', function() {
var calendarEl = document.getElementById('calendar');
var calendar = new FullCalendar.Calendar(calendarEl, {
headerToolbar: {
left: 'prev,next today',
center: 'title',
right: 'dayGridMonth,timeGridWeek'
},
events: function(start, end, timezone, callback) {
$.ajax({
url: '<?php echo site_url("absentMonthYearController/absentYearController/calendarShow/" . $nik) ?>',
type: 'GET',
dataType: 'JSON',
success: function(data) {
var events = [];
if (data != null) {
$.each(data, function(i, item) {
events.push({
start: item.date,
title: 'Present',
display: 'background'
})
})
}
console.log('events', events);
}
})
}
});
calendar.render();
});
the data doesn't appear in the calendar, but it does appear in console.log
There are two issues here:
events: function(start, end, timezone, callback) { is wrong for fullCalendar 5. That looks like the syntax from an earlier version. https://fullcalendar.io/docs/v5/events-function shows the function's signature in v5, which is
function( fetchInfo, successCallback, failureCallback ) {
You forgot to use the provided callback to return the events to fullCalendar. So your function is downloading the events and logging them, but they never make it to the calendar.
Therefore this:
events: function( fetchInfo, successCallback, failureCallback ) {
$.ajax({
url: '<?php echo site_url("absentMonthYearController/absentYearController/calendarShow/" . $nik) ?>',
type: 'GET',
dataType: 'JSON',
success: function(data) {
var events = [];
if (data != null) {
$.each(data, function(i, item) {
events.push({
start: item.date,
title: 'Present',
display: 'background'
})
})
}
console.log('events', events);
successCallback(events);
}
})
}
should fix it.
P.S. Really you should also be using the start and end dates provided inside the fetchInfo object to send to your server, and the server should be using them to restrict the events it returns to only those which occur (or overlap) within those dates. That way you don't return a large number of events which mostly never get viewed, instead you only return what's relevant to the date range bein displayed.
Related
I am using fullcalendar v4 (https://fullcalendar.io/) and I am trying to delete events when the event is clicked.
When I click on an event, I have this code to delete the event:
document.addEventListener('DOMContentLoaded', function() {
var calendarEl = document.getElementById('calendar');
var calendar = new FullCalendar.Calendar(calendarEl, {
locale: 'pt',
plugins: [ 'interaction', 'dayGrid', 'timeGrid', 'list' ],
editable: true,
header: {
left: 'prev,next today',
center: 'title',
right: 'dayGridMonth,timeGridWeek,timeGridDay,listWeek'
},
// CUSTOM CODE DATABASE
events: load.php,
eventClick:function(clickedInfo)
{
if(confirm("Are you sure you want to delete this event?"))
{
var id = clickedInfo.event.id;
$.ajax({
url:"delete.php",
type:"POST",
data:{id:id},
success: function() {
alert('Deleted!');
calendar.refetchEvents();
}
})
}
},
});
calendar.render();
});
The event is getting deleted in the database, so the function works fine, but the events don't refresh and the deleted event is still showing in the calendar. It only disappears when I fully refresh the page, which is not ideal.
Any idea why?
It doesn't look like the calendar object is ever being initialized.
I would try changing your event listener as described in the documentation:
document.addEventListener('DOMContentLoaded', function() {
var calendarEl = document.getElementById('calendar');
var calendar = new FullCalendar.Calendar(calendarEl, {
plugins: [ 'dayGrid' ]
});
calendar.render();
});
Ref. https://fullcalendar.io/docs/initialize-globals
I am assuming you are using script tags, but if you're using a build system (i.e. webpack), then you can try this: https://fullcalendar.io/docs/initialize-es6
For removing an event, I would just try this:
eventClick:function(clickedInfo)
{
if(confirm("Are you sure you want to delete this event?"))
{
var id = clickedInfo.event.id;
$.ajax({
url:"delete.php",
type:"POST",
data:{id:id},
success: function() {
alert('Deleted!');
//calendar.refetchEvents(); // remove this
clickedInfo.event.remove(); // try this instead
}
})
}
},
Ref. https://fullcalendar.io/docs/Event-remove
I'm trying to make this code to work but it look I'm doing something wrong when passing the two variables with ajax, please help, here is the code, basically is a drag and drop code to move items between boxes and organize inside each box.
<script type="text/javascript">
$(document).ready(function() {
// Example 1.3: Sortable and connectable lists with visual helper
$('#sortable-div .sortable-list').sortable({
connectWith: '#sortable-div .sortable-list',
placeholder: 'placeholder',
delay: 150,
stop: function() {
var selectedData = new Array();
$('.sortable-list>li').each(function() {
selectedData.push([$(this).attr("id"), $(this).attr("pagenum")])
});
updateOrder(selectedData);
}
});
});
function updateOrder(data) {
$.ajax({
url: "ajaxPro.php",
type: 'post',
data: {
position: data,
page: data
},
success: function() {
/* alert('your change successfully saved');*/
}
})
}
</script>
You can make it using this way:
$('.spremiUredivanje').click(function(){
ai = document.getElementById('ai_mjerila_edit').value;
broj_mjerila = document.getElementById('broj_mjerila_edit').value;
adresa = document.getElementById('adresa_edit').value;
stanje = document.getElementById('stanje_edit').value;
$( "#datum_edit" ).datepicker( "option", "dateFormat", "yy-mm-dd" );
datum = document.getElementById('datum_edit').value;
operater = document.getElementById('operater_edit').value;
$.ajax({
url: 'test.php',
type: 'POST',
data: {
post1: broj_mjerila, post2: adresa, post3:stanje, post4: datum, post5: operater, post6:ai
},
beforeSend: function(){
$('#loaderEdit').show();
},
So your php file should look like this:
$broj_mjerila = $_POST['post1'];
$adresa = $_POST['post2'];
$stanje = $_POST['post3'];
$datum = $_POST['post4'];
$operater = $_POST['post5'];
$ai = $_POST['post6'];
To control your response use success inside ajax call:
success: function(response) {
if(response == 1) {
//alert("success!");
$('#editUspjesan').show();
$('#loaderEdit').hide();...
Can you explain your requirement clear. Are you trying to get page number and id in 2 separate array?
// If page no and id need to be in separate array
var position = [], pages = [];
$('.sortable-list>li').each(function() {
position.push($(this).attr("id"));
pages.push($(this).attr("pagenum"));
});
updateOrder(position, pages);
function updateOrder(position, page) {
$.ajax({
url: "ajaxPro.php",
type: 'post',
data: {
position: position,
page: page
},
success: function() {
/* alert('your change successfully saved');*/
}
})
}
// If page no and id can be combined use objects
var selectedData = [];
$('.sortable-list>li').each(function() {
selectedData.push({id: $(this).attr("id"), page: $(this).attr("pagenum")})
});
function updateOrder(data) {
$.ajax({
url: "ajaxPro.php",
type: 'post',
data: {
position: data
},
success: function() {
/* alert('your change successfully saved');*/
}
})
}
<script type="text/javascript">
$(document).ready(function() {
// Example 1.3: Sortable and connectable lists with visual helper
$('#sortable-div .sortable-list').sortable({
connectWith: '#sortable-div .sortable-list',
placeholder: 'placeholder',
delay: 150,
stop: function() {
var selectedData = new Array();
$('.sortable-list>li').each(function() {
selectedData.push([$(this).attr("id"), $(this).attr("pagenum")])
});
updateOrder(selectedData);
}
});
});
function updateOrder(data) {
$.ajax({
url: "ajaxPro.php",
type: 'post',
data: {
position: data.id,
page: data.pagenum
},
dataType:'json',
success: function() {
/* alert('your change successfully saved');*/
}
})
}
</script>
Let's try this one
I'd like to color events according to database. I use eventRender. Here is the whole code:
$(document).ready(function() {
var date = new Date();
var calendar = $('#calendar').fullCalendar({
header:
{
left: 'prev,next ',
center: 'title',
right: 'today'
},
selectable: true,
selectHelper: true,
fixedWeekCount: false,
allDayDefault: true,
editable: true,
events: "http://localhost/calendar_directory/calendar_db_connect.php",
eventRender: function (event, element, view)
{
if (event.confirmed == 0)
{
event.color = "#FFB999";
}
else
{
event.color = "#528881";
}
},
select: function(start, end) {
var title;
var beforeToday = false;
var check = $.fullCalendar.formatDate(start, "YYYY-MM-DD");
var today = $.fullCalendar.formatDate(moment(), "YYYY-MM-DD");
if(check < today)
{
beforeToday = true;
}
else
{
title = prompt('Event Title:');
}
if (title && !beforeToday)
{
var start = $.fullCalendar.formatDate(start, "YYYY-MM-DD");
var end = $.fullCalendar.formatDate(end, "YYYY-MM-DD");
$.ajax(
{
url: 'http://localhost/calendar_directory/add_events.php',
data: 'title='+ title+'&start='+ start +'&end='+ end ,
type: "POST",
success: function(json)
{
}
});
calendar.fullCalendar('renderEvent',
{
title: title,
start: start,
end: end,
},
true // make the event "stick"
);
}
calendar.fullCalendar('unselect');
},
eventClick: function(event, jsEvent, view)
{
//set the values and open the modal
$("#eventInfo").html(event.description);
$("#eventLink").attr('href', event.url);
$("#eventContent").dialog({ modal: true, title: event.title });
},
eventDrop: function(event, delta)
{
var check = $.fullCalendar.formatDate(event.start, "YYYY-MM-DD");
var today = $.fullCalendar.formatDate(moment(), "YYYY-MM-DD");
if(check < today) {
alert('Select an other start time, after today!');
}
else
{
var start = $.fullCalendar.formatDate(event.start, "YYYY-MM-DD");
var end = $.fullCalendar.formatDate(event.end, "YYYY-MM-DD");
$.ajax(
{
url: 'http://localhost/calendar_directory/update_events.php',
data: 'title='+ event.title+'&start='+ start +'&end='+ end +'&id='+ event.id ,
type: "POST",
});
}
},
eventResize: function(event)
{
var start = $.fullCalendar.formatDate(event.start, "YYYY-MM-DD");
var end = $.fullCalendar.formatDate(event.end, "YYYY-MM-DD");
$.ajax(
{
url: 'http://localhost/calendar_directory/update_events.php',
data: 'title='+ event.title+'&start='+ start +'&end='+ end +'&id='+ event.id ,
type: "POST",
});
},
eventClick: function(event)
{
var decision = confirm("Do you really want to confirm that?");
if (decision)
{
$.ajax(
{
url: "http://localhost/calendar_directory/confirm_events.php",
data: "&id=" + event.id,
type: "POST",
success: function(json)
{
console.log("confirmed");
//event.backgroundColor = 'green';
//$('#calendar').fullCalendar( 'rerenderEvents' );
}
});
}
}
});
(Please ignore clickEvent for modal).
The problem is, that it does not change the color of the events for the first time (first load of the page). But when I drop/resize an event all events gets the right color.
Before drop
After drop
table structure:
id - int, PR
title - varchar
start -datetime
end -datetime
confirmed - int (can be 0 or 1) <- The color should be change according to this
The eventRender method runs after the corresponding CSS for the event has been created. Therefore changing the properties of the event which relate to formatting/rendering at this point in the process has no effect - they have already been processed.
Luckily, you also get the "element" parameter passed to you in the callback - this gives you access to the rendered HTML, which you can then manipulate.
Setting the "color" property of an event actually affects the background and border colours of the rendered element, so we can replace what you did with:
eventRender: function (event, element, view)
{
if (event.confirmed == 0)
{
element.css("background-color", "#FFB999");
element.css("border-color", "#FFB999");
}
else
{
element.css("background-color", "#528881");
element.css("border-color", "#528881");
}
}
This should have the desired effect. Arguably this is a bug/undesirable feature in fullCalendar - you'd want to still be able to manipulate the event's properties fully and expect them to take effect. On the other hand, getting the "element" parameter effectively gives you full control over the rendering of the event, more than you would just via setting the event's properties. If this method ran before the element was created, you wouldn't have access to the element, with all the extra power that gives you. So it's a trade-off, but it's worth understanding the internals in order to know what you can change, and when in the process you can do it.
I'm using FullCalendar in my Symfony project and I want to load events from database and show them in calendar for user.
According to documentation I have create a AJAX request to server on my calendar.html.twig page and store response in localStorage. This is what I done:
$(document).ready(function () {
var events = [];
$.ajax({
url: '{{ path('property.get.reservations') }}',
method: 'post',
data: {
'propertyId': {{ propertyId }}
}, success: function (data) {
console.log('running script within calendar.html.twig')
$.each(data, function (key, value) {
var event = JSON.stringify(value);
events.push(event);
});
localStorage.setItem('events', events);
}
});
});
Next I'm trying to use this storaged data in my calnedarService.js in this way:
$('#calendar').fullCalendar({
selectable: false,
header: {
left: 'prev,next',
center: 'title',
right: ''
},
editable: true,
events: localStorage.getItem('events'),
/* another code */
I get an error in the console:
No route found for "GET /admin/property/edit/1/%7B%22id%22:1,%22start%22:%222016-12-04T00:00:00.000Z%22,%22end%22:%222016-12-07T00:00:00.000Z%22%7D" (from "my_host")
So, for the reasons which I don't know,fullCalendar try to generate route, using parameters, getting from AJAX.
Any help will appreciated
Worked for me, just put this for url :
'admin/property/edit/'
with the id var at the end of the url
I successfully store and retrive event from database using ajax now how to show this into events in fullcalnder??
Saving event in Database: Using Ajax.
$('#calendar').fullCalendar({
header: {
left: 'prev,next today',
center: 'title',
right: 'month,agendaWeek,agendaDay'
},
defaultDate: '2015-02-12',
selectable: true,
selectHelper: true,
select: function(start, end) {
var title = prompt('Event Title:');
var eventData;
if (title) {
eventData = {
title: title,
start: start,
end: end
};
$.ajax ({
url: "http://localhost/phplec/sms/calendar/test",
type: 'POST',
data: {'title': title, 'start' : start.format(), 'end': end.format()},
success: function(msg) {
alert(msg);
}
});
Controller: Here i Accept Ajax request and connect to DB
function test() {
$this->load->model('calendar_model');
$data = array(
'title' => $_POST['title'],
'start' => $_POST['start'],
'end' => $_POST['end']
);
$this->calendar_model->add_record($data);
echo "working";
}
Now I want To show my database in fullCalander on page laod.
I successfully get event from database and convet it into json now how to show it on view.
function get_records()
{
$data = $this->db->get("calendar_test");
$json_data = json_encode($data->result_array());
var_dump($json_data);
}
How i Show this event Dynamically
$.ajax ({
url: "http://localhost/phplec/sms/calendar/get_records",
type: 'GET',
dataType: "html", //expect html to be returned
success: function(response){
alert(response)
}
I successfully get event json in fullcalander.js now how to pass this to events.
OK from what I understand you want to click on a calendar day, it prompts you for a title, then you submit the data to the DB and then you want to see it again. These are the steps you need to take:
you need to use the events method so that fullcalendar knows how to fetch events when its loaded, like this:
$('#calendar').fullCalendar({
// ....your other methods...
events: 'http://localhost/phplec/sms/calendar/get_records' //this should echo out JSON
});
after your ajax succesfully saves the events in the database, then call the refetchEvents method like this:
$('#calendar').fullCalendar('refetchEvents');
In the end, this is how I would do it:
var myCalendar = $('#calendar').fullCalendar({
header: {
left: 'prev,next today',
center: 'title',
right: 'month,agendaWeek,agendaDay'
},
events: 'http://localhost/phplec/sms/calendar/get_records',
defaultDate: '2015-02-12',
selectable: true,
selectHelper: true,
select: function(start, end) {
var title = prompt('Event Title:');
if (title) {
var eventData = {
title: title,
start: start.format(),
end: end.format()
};
$.ajax({
url: "http://localhost/phplec/sms/calendar/test",
type: 'POST',
data: eventData,
success: function(result) {
if(result === "working"){
myCalendar.fullCalendar('refetchEvents');
}else{
alert("Error Message");
}
},
error: function(xhr, status, msg) {
alert(msg);
}
});
}
}
});