Add Event to Calendar in fullcalendar - javascript

I have a problem again and do not really get on with it.
I would like to know that you can enter an appointment and I already have the following script.
Unfortunately, no entries are entered in the calendar :-( can someone help me there?
I've already asked quite a bit about google and co. Unfortunately, I come to no real point of help.
can it be that I already use the eventRender and then want to use it again below?
here once my code:
<link rel='stylesheet' href='kalender2/fullcalendar.css' />
<script src='kalender2/fullcalendar.js'></script>
<script src='kalender2/locale/de.js'></script>
<script src="js/bootstrap.min.js"></script>
<script src="js/bootstrap.bundle.min.js"></script>
<script src="kalender2/lib/hour.js"></script>
<script>
var CalenderEvent;
var datenPruefenDatenSenden;
var terminPruefenDatenSenden;
var datenPruefenDatenVerarbeiten;
var termin_nachberechnung;
var TerminAddZeit;
var AddEventToCalener;
$(document).ready(function() {
function DeleteEvent(id){
SendFormData(id,'',"delete");
$('#calendar').fullCalendar('removeEvents',id);
}
var initialLocaleCode = 'de';
$('#calendar').fullCalendar({
header: {
left: 'prev,next today',
center: 'title',
right: 'month,agendaWeek,agendaDay,listWeek'
},
dayClick: function(date, jsEvent, view) {
$('#calenderAdEvent').modal('show');
$('#start_date_add_day').val(date.format('DD.MM.YYYY'));
$('#start_date_add_time').val(date.format('HH:mm'));
},
eventRender: function(eventObj, $el) {
$el.popover({
title: eventObj.title,
content: eventObj.description,
trigger: 'hover',
placement: 'top',
container: 'body'
});
$el.html(eventObj.title + '<span class="removebtn" onclick="DeleteEvent('+eventObj.id+');" id="Delete">X</span>');
$el.find(".removebtn").click(function() {
$('#calendar').fullCalendar('removeEvents',eventObj.id);
});
},
businessHours: [
<?php echo $Offen;?>
],
eventDrop: function( event, delta, revertFunc, jsEvent, ui, view ) {
var Alertback = SendFormData(event.id,$.fullCalendar.moment(event.start._d), $.fullCalendar.moment(event.end._d),"update");
alert(Alertback);
},
eventResize: function( event, delta, revertFunc, jsEvent, ui, view ) {
var Alertback = SendFormData(event.id,$.fullCalendar.moment(event.start._d), $.fullCalendar.moment(event.end._d),"update");
alert(Alertback);
},
timezone: 'Europe/Berlin',
nowIndicator: true,
now: '<?php echo date("Y-m-d", time() ) .'T'. date("H:i:s");?>',
locale: 'de',
buttonIcons: true, // show the prev/next text
defaultView: 'agendaWeek',
defaultDate: '<?php echo date("Y-m-d", time() );?>',
navLinks: true, // can click day/week names to navigate views
editable: true,
eventLimit: true, // allow "more" link when too many events
allDaySlot: true,
droppable: true,
events: [
<?php echo $aus;?>
],
timeFormat: 'H(:mm)',
eventClick: function(event, jsEvent, view) {
CalenderEvent = event;
$('#id_termin').val(event.id);
$('#name').val(event.title);
$('#Time_Event').val(event.TimeEvent);
$('#description').val(event.description);
$('#start_date_day').val(moment(event.start).format('DD.MM.YYYY'));
$('#start_date_time').val(moment(event.start).format('HH:mm'));
if(event.end) {
$('#end_date_day').val(moment(event.end).format('DD.MM.YYYY'));
$('#end_date_time').val(moment(event.end).format('HH:mm'));
} else {
$('#end_date_day').val(moment(event.end).format('DD.MM.YYYY'));
$('#end_date_time').val(moment(event.end).format('HH:mm'));
}
$('#event_id').val(event.id);
$('#calenderEditEvent').modal();
}
});
datenPruefenDatenSenden = function(){
var start = $('#start_date_day').val()+'//'+$('#start_date_time').val();
var end = $('#end_date_day').val()+'//'+$('#end_date_time').val();
var erg = SendFormData($("#id_termin").val(),start,end,'TerminEditSave');
$('#calenderEditEvent').modal('hide');
CalenderEvent.start = moment($('#start_date_day').val()+' '+$('#start_date_time').val(), "DD.MM.YYYY HH:MM");
CalenderEvent.end = moment($('#end_date_day').val()+' '+$('#end_date_time').val(), "DD.MM.YYYY HH:MM");
$('#calendar').fullCalendar('updateEvent', CalenderEvent);
}
datenPruefenDatenVerarbeiten = function (daten){
if(daten == 1){$('#submit_erg').html('<div class="alert alert-danger">Terminüberschneidung</div><button class="btn btn-info" onclick="terminPruefenDatenSenden();">Erneut prüfen</button>');}
$('#submit_button').html('<button type="button" class="btn btn-warning" onclick="datenPruefenDatenSenden();">Termin Speichern</button>');
}
terminPruefenDatenSenden = function (){
$('#submit_erg').html('');
var start = $('#start_date_day').val()+'//'+$('#start_date_time').val();
var end = $('#end_date_day').val()+'//'+$('#end_date_time').val();
var erg = SendFormData($("#id_termin").val(),start,end,'pruefen');
}
termin_nachberechnung = function (){
var TimePlus = new Hour($('#Time_Event').val());
var zeit = new Hour($('#start_date_time').val()+':00');
$('#end_date_time').val(zeit.add(TimePlus));
}
TerminAddZeit = function (){
var erg = SendFormData($("#id_termin_add").val(),$('#start_date_add_time').val(),'','TimePlus');
$('#start_date_add_time_end').val(erg);
}
AddEventToCalener = function(){
var Start = moment($('#start_date_add_day').val()+' '+$('#start_date_add_time').val(), "DD.MM.YYYY HH:MM");
var End = moment($('#start_date_add_day').val()+' '+$('#start_date_add_time_end').val(), "DD.MM.YYYY HH:MM");
var event = new Object();
event = {
title: 'Testtermin',
start: Start,
end: End,
allDay: false,
};
console.log(event);
$('#calendar').fullCalendar('renderEvent', event);
}
});
$(function() {
$('[data-toggle="datepicker_bearbeiten"]').datepicker({
autoHide: true,
format: 'dd.mm.yyyy',
zIndex: 2048,
});
});
function SendFormData(id,start,end,aufruf){
var erg;
if(aufruf == 'update'){start = start/1000;end = end/1000;}
$.ajax({type: "post",url: "kalender2/kalender.class.php",data : {id : id,sta : start,end : end,aufruf : aufruf}
}).done(function( dataEnd ){if(aufruf == 'pruefen'){datenPruefenDatenVerarbeiten(dataEnd);}erg = dataEnd;});
return erg;
}
</script>
<div id='calendar'></div>
<div class="modal" id="calenderAdEvent" tabindex="-1" role="dialog">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Termin eintragen</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div class="input-group mb-3">
<div class="input-group-prepend">
<span class="input-group-text">Datum</span>
</div>
<input type="text" id="start_date_add_day" name="start_date_add_day" class="form-control">
</div>
<div class="input-group mb-3">
<div class="input-group-prepend">
<span class="input-group-text">Dienstleistung</span>
</div>
<select class="custom-select" id="id_termin_add">
<option selected>bitte wählen</option>
<?php echo $dienst;?>
</select>
</div>
<div class="input-group mb-3">
<div class="input-group-prepend">
<span class="input-group-text">Termin von</span>
</div>
<input type="text" id="start_date_add_time" name="start_date_add_time" class="form-control">
<div class="input-group-append">
<span class="input-group-text">-</span>
</div>
<input type="text" name="start_date_add_time_end" id="start_date_add_time_end" class="form-control">
</div>
<div class="input-group mb-3">
<div class="input-group-prepend">
<span class="input-group-text">Kundenname</span>
</div>
<input type="text" list="kunden" id="KundenName" name="KundenName" class="form-control" onkeyup="KundenListe();">
<datalist id="kunden">
<?php echo $KundenListe;?>
</datalist>
<div class="input-group-append">
<span class="input-group-text">oder KN</span>
</div>
<input type="text" name="KIDTerminBuchen" id="KIDTerminBuchen" class="form-control">
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary" onclick="AddEventToCalener();">Save changes</button>
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<div class="modal" id="calenderEditEvent" tabindex="-1" role="dialog">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Termin bearbeiten</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div class="input-group mb-3">
<div class="input-group-prepend">
<span class="input-group-text" id="basic-addon1">Start</span>
</div>
<input type="text" name="termin" id="start_date_day" class="form-control" data-toggle="datepicker_bearbeiten">
<input type="text" id="start_date_time" onkeyup="termin_nachberechnung('Hallo');" class="form-control datetimepicker-input" data-target="#datetimepicker3" data-target-input="nearest"/>
<div class="input-group-append">
<span class="input-group-text">
<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABkAAAAZCAYAAADE6YVjAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAHfSURBVEhLzZW9L91hFMcvaby0HUi9VKJNE2ZbvWxERQdTO5h0YLCQWLAykehUJAYWIWZSjBJtojqQog1TUyotwl8g+HyfU7fXffm9Mfgkn+ScJzf3/J7n+Z3zi90HHuBrnMBveITneIhfcRhrMDJvcA8/Yw9W4RPMxqdYiwP4A1cwVLFcnMYNrNdCAtrZOwvjqGgb7mOfFvzIwU84g3laSOI5/rIwhTJcw1GXeaAdqECWy1LxKiIeok6gy2VpeIubmG4H1/gVEeX4FytcloDOehcbXJaZIEWE7mbOwv/oNV210JOgRXQap1jisn+oD/Sa+hG0iJjFDguNLVQf+BGmiApMWmgcoxrNDz3dBfa7zJsmXLbQ0KhQU3mhJlWBS9zWgg/VqL6J8wdLLcxIJ+p3O9iqBR9acN5CYx01izKhAj/xhcuCoYYct9AYwkELU4hSQHxEDdk4Or/vmHwvypcwbIFiPMPHLktA4zp5wkblA45YeBPtRuNa0/Q26G41uwpdloZe/IKPXBYeNetvbHSZB2Oocf3MZcGpwwO8MUq80Oun77l2lq8FD4pQD6bv/isthKESNa5PUB+ydmzGl6hG68ZF1LR9jwUYGY1rHcEU6k/VuAuoRlMfRL2/uyQWuwKiRlWN6WWKKwAAAABJRU5ErkJggg==">
</span>
</div>
</div>
<div class="input-group mb-3">
<div class="input-group-prepend">
<span class="input-group-text" id="basic-addon1">Ende</span>
</div>
<input type="text" name="termin" id="end_date_day" class="form-control" data-toggle="datepicker_bearbeiten">
<input type="text" id="end_date_time" class="form-control datetimepicker-input" data-target="#datetimepicker3" data-target-input="nearest"/>
<div class="input-group-append">
<span class="input-group-text">
<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABkAAAAZCAYAAADE6YVjAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAHfSURBVEhLzZW9L91hFMcvaby0HUi9VKJNE2ZbvWxERQdTO5h0YLCQWLAykehUJAYWIWZSjBJtojqQog1TUyotwl8g+HyfU7fXffm9Mfgkn+ScJzf3/J7n+Z3zi90HHuBrnMBveITneIhfcRhrMDJvcA8/Yw9W4RPMxqdYiwP4A1cwVLFcnMYNrNdCAtrZOwvjqGgb7mOfFvzIwU84g3laSOI5/rIwhTJcw1GXeaAdqECWy1LxKiIeok6gy2VpeIubmG4H1/gVEeX4FytcloDOehcbXJaZIEWE7mbOwv/oNV210JOgRXQap1jisn+oD/Sa+hG0iJjFDguNLVQf+BGmiApMWmgcoxrNDz3dBfa7zJsmXLbQ0KhQU3mhJlWBS9zWgg/VqL6J8wdLLcxIJ+p3O9iqBR9acN5CYx01izKhAj/xhcuCoYYct9AYwkELU4hSQHxEDdk4Or/vmHwvypcwbIFiPMPHLktA4zp5wkblA45YeBPtRuNa0/Q26G41uwpdloZe/IKPXBYeNetvbHSZB2Oocf3MZcGpwwO8MUq80Oun77l2lq8FD4pQD6bv/isthKESNa5PUB+ydmzGl6hG68ZF1LR9jwUYGY1rHcEU6k/VuAuoRlMfRL2/uyQWuwKiRlWN6WWKKwAAAABJRU5ErkJggg==">
</span>
</div>
</div>
<input type="hidden" id="id_termin">
<input type="hidden" id="Time_Event">
</div>
<div class="modal-footer">
<span id="submit_erg"></span>
<span id="submit_button"><button type="button" class="btn btn-info" onclick="terminPruefenDatenSenden();">Prüfen</button></span>
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
I have done some more tests. As soon as I take the eventRender: function (eventObj, $ el) { ........ }, out, I use the function AddEventToCalener = function () { $ ('# calendar'). fullCalendar ('renderEvent', { title: 'dynamic event', start: '2018-11-26', allDay: true }); } successfully.
But as soon as I insert eventRender again, I get the following message:
Error: TOOLTIP: Option "content" provided type "undefined" but
expected type "(string | element | function)"
So the problem is still that the event is not entered in the calendar. the console gives me the following with console.log
{…} ​ allDay: false ​ end: Object { _isAMomentObject: true, _i: "26.11.2018 12:00", _f: "DD.MM.YYYY HH:MM", … } ​ start: Object { _isAMomentObject: true, _i: "26.11.2018 11:30", _f: "DD.MM.YYYY HH:MM", … } ​ title: "Testtermin" ​ <prototype>: Object { … }

Your code is failing to add the event because of a missing field.
In the eventRender function you create a popover, and the popover tries to read a property called "description" from the event:
content: eventObj.description
However, your AddEventToCalener() function defines an event like this:
event = {
title: 'Testtermin',
start: Start,
end: End,
allDay: false,
};
In this event there is no "description" field specified. This means it's undefined, and therefore when eventRender runs and tries to create the popover, it crashes because it can't read that field. (I know this from the error message - it appears the popover code is programmed to check the type of the value given in the "content" option, and will only accept strings, HTML elements, or functions - it will not accept undefined variables.)
For the eventRender/popover code to work you need to specify something for the field, even if it's just an empty string:
event = {
title: 'Testtermin',
start: Start,
end: End,
allDay: false,
description: ""
};
Also, your momentJS parsing string is incorrect - instead of
"DD.MM.YYYY HH:MM"
it should be
"DD.MM.YYYY HH:mm"
because MM signifies months, whereas mm signifies minutes. See http://momentjs.com/docs/#/parsing/string-format/ for documenation.

Fullcalendar v5
let calendarEl = document.getElementById('calendar');
let calendar = new FullCalendar.Calendar(calendarEl, {
dateClick: function(date) {
console.log(date);
console.log(date.jsEvent);
console.log(date.view);
},
})

Related

change style through checkbox

I'm working ona fullcalendar project.
I have these 2 checkboxes (Ore Personali e Assenze), when they are checked they should hide the events but at the moment they are not doing it.
This is my input checkbox:
<input type="checkbox" id="OP" name="calendario" value="OP">
And this is the function i've build so far:
$(document).ready(function() {
$('input[type="checkbox"]').click(function() {
var checkBox = document.getElementById("OP");
var x = document.getElementsByClassName("fc-event-container");
if (checkBox.checked === true){
x.style.visibility = "visible !important";
}else{
x.style.visibility = "hidden !important";
}
})
})
I build it by looking on the internet cause i'm new to JS and dont know much, just basic stuff.
And it's giving error in the x.style part (telling me is undefined).
Can someone explain to me how i should do it, cause on internet i only found this way and some other who's just giving me errors anyway.
thanks in advances whos gonna help me (or at least try)
i did as #Cypherjac suggest and it worked.
But now it just hide the events on the current month, when i change months i have to checked and unchecked to hide. Even if i go back to the month i hid the events they are visible
Is there a way to let them stay hide even if i change month?
Before i update the code i will specify that this is not my code, my fullcalendar is from a template i found on internet, i add the function i needed but most of th stuff was already there:
calendar.js code:
key: 'handleFullcalendar',
value: function handleFullcalendar() {
var myOptions = {
header: {
left: 'today',
center: 'prev,title,next',
right: 'none',
},
buttonText:{
today: 'Oggi',
month: 'Mese',
week: 'Settimana',
day: 'Giorno'
},
locale:'it',
allDaySlot: false,
selectable: true,
selectHelper: true,
timeFormat: 'H(:mm)',
editable: true,
eventLimit: true,
resourceAreaHeaderContent: 'Calendari',
resources: [
{
id: 'a',
title: 'Ore Personali'
},
{
id: 'b',
title: 'Assenze'
}
],
windowResize: function windowResize(view) {
var width = $(window).outerWidth();
var options = Object.assign({}, myOptions);
options.events = view.calendar.clientEvents();
options.aspectRatio = width < 667 ? 0.5 : 1.35;
$('#calendar').fullCalendar('destroy');
$('#calendar').fullCalendar(options);
},
//_______apre modal per aggiungere nuovo evento
select: function select(event) {
$('#addNewEvent').modal('show');
$('#calendar').fullCalendar('refetchEvents',event._id)
},
//_______________ELIMINARE EVENTO TRAMITE X
eventRender: function(event, element, view) {
if (view.name == 'listDay') {
element.find(".fc-list-item-time").append("<span class='closeon'>X</span>");
} else {
element.find(".fc-content").prepend("<span class='closeon'>X</span>");
}
element.find(".closeon").on('click', function() {
var deleteMsg = confirm("Vuoi davvero eliminare " + event.title + "?");
if (deleteMsg == true) {
$.ajax({
url: 'eventi/deleteEvent.php',
type: 'POST',
data: {_id: event.idAssenza, nomeUtente: event.nomeUtente},
success: function(html){
location.reload();
}
})
$('#calendar').fullCalendar('removeEvents',event._id);
}else{
location.reload();
}
})
},
//triggherà apertura modal di #editEvent
eventClick: function eventClick(event) {
var color = event.backgroundColor ? event.backgroundColor : (0, _Config.colors)('blue', 600);
$('#editEname').val(event.title);
$('event.id').val(event.idAssenza);
$('nomeUtente').val(event.nomeUtente);
$('#editStarts').val(event.start.toISOString());
$('#editEnds').val(event.end.toISOString());
$('#editNewEvent').modal('show').one('hidden.bs.modal', function (e) {
event.title = $('#editEname').val();
event.start = $('#editStarts').val();
event.end = $('#editEnds').val();
$.ajax({
url: 'eventi/updateEvent.php',
type: 'POST',
data: {start: event.start, _id: event.idAssenza, end: event.end, title: event.title, },
success: function(html){
location.reload();
}
});
$('#calendar').fullCalendar('updateEvent', event._id);
});
},
events: {
url: 'eventi/load.php',
method:'POST'
//color: <- fare in modo che prenda i colori scelti nel modal
},
droppable: false
};
{
$(function() {
$('#OP').change(function() {
var x = $('.fc-event-container');
// Access the element using jQuery
if($(this).prop('checked')){
x.css({
'visibility': 'visible'
})
}
else {
x.css({
'visibility': 'hidden'
})
}
})
});
},
var _options = void 0;
var myOptionsMobile = Object.assign({}, myOptions);
myOptionsMobile.aspectRatio = 0.5;
_options = $(window).outerWidth() < 667 ? myOptionsMobile : myOptions;
$('#editNewEvent').modal();
$('#calendar').fullCalendar(_options);
}
Calendar.php:
<?php
require_once "config.php";
session_start();
if(!ISSET($_SESSION['nomeUtente'])){
header('location:login/login.php');
}
?>
<!DOCTYPE html>
<html class="no-js css-menubar" locale="it">
<head>
<!-- Meta Tag -->
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimal-ui">
<meta name="description" content="bootstrap material admin template">
<meta name="author" content="">
<title> Calendario | E.D. Elettronica Dedicata </title>
</head>
<body>
<div class="page">
<div class="page-aside">
<div class="page-aside-switch">
<i class="icon md-chevron-left" aria-hidden="true"></i>
<i class="icon md-chevron-right" aria-hidden="true"></i>
</div>
<div class="page-aside-inner page-aside-scroll">
<div data-role="container">
<div data-role="content">
<!--LISTA CALENDARI-->
<section class="page-aside-section">
<h5 class="page-aside-title">Lista calendari di <?php echo $_SESSION["nomeUtente"]; ?></h5>
<div class="list-group has-actions">
<div class="list-group-item" data-plugin="editlist">
<div class="list-content">
<input type="checkbox" id="OP" name="calendario" value="OP" checked>
<span class="list-text">Ore Personali</span>
</div>
</div>
<div class="list-group-item" data-plugin="editlist">
<div class="list-content">
<input type="checkbox" id="assenze" name="calendario" value="assenze">
<span class="list-text">Assenze</span>
</div>
<div class="list-editable">
</div>
</div>
</div>
</section>
</div>
</div>
</div>
</div>
<div class="page-main">
<div class="calendar-container">
<div id="calendar"></div>
<!--addEvent Dialog -->
<div class="modal fade" id="addNewEvent" aria-hidden="true" aria-labelledby="addNewEvent"
role="dialog" tabindex="-1">
<div class="modal-dialog modal-simple">
<form class="modal-content form-horizontal" action="eventi/addEvent.php" method="post" role="form">
<div class="modal-header">
<button type="button" class="close" aria-hidden="true" data-dismiss="modal">×</button>
<h4 class="modal-title">Aggiungi Assenza (<?php echo $_SESSION["nomeUtente"]; ?>)</h4>
</div>
<div class="modal-body">
<div class="form-group row" id=editColor>
<label class="form-control-label col-md-2">Tipo:</label>
<input list="assenza" name="ename" id="ename" style="margin-left: 15px;" />
<datalist id="assenza">
<option value="Normali">
<option value="Straordinarie">
<option value="Ferie">
<option value="Malattia">
<option value="Permesso">
<option value="Smart Working">
<option value="Altro">
</datalist>
<input type="hidden" name="nomeUtente" id="nomeUtente" value="<?php echo $_SESSION["nomeUtente"]; ?>">
</div>
<div class="form-group row">
<label class="col-md-2 form-control-label" for="starts">Inizio:</label>
<div class="col-md-10">
<div class="input-group">
<input type="datetime-local" class="form-control" id="starts" name="starts" data-container="#addNewEvent">
</div>
</div>
</div>
<div class="form-group row">
<label class="col-md-2 form-control-label" for="ends">Fine:</label>
<div class="col-md-10">
<div class="input-group">
<input type="datetime-local" class="form-control" id="ends" name="ends" data-container="#addNewEvent">
</div>
</div>
</div>
</div>
<div class="modal-footer">
<div class="form-actions">
<input type="submit" class="btn btn-primary" value="Aggiungi Assenza">
<a class="btn btn-sm btn-white btn-pure" data-dismiss="modal" href="javascript:void(0)">Annulla</a>
</div>
</div>
</form>
</div>
</div>
<!-- End AddEvent Dialog -->
<!-- editEvent Dialog -->
<div class="modal fade" id="editNewEvent" aria-hidden="true" aria-labelledby="editNewEvent"
role="dialog" tabindex="-1" data-show="false">
<div class="modal-dialog modal-simple">
<form class="modal-content form-horizontal" action="eventi/deleteEvent.php" method="POST" role="form">
<div class="modal-header">
<button type="button" class="close" aria-hidden="true" data-dismiss="modal">×</button>
<h4 class="modal-title">Modifica Assenza (<?php echo $_SESSION["nomeUtente"]; ?>)</h4>
</div>
<div class="modal-body">
<div class="form-group row">
<label class="form-control-label col-md-2" for="editEname">Tipo:</label>
<input list="assenza" name="editEname" id="editEname" style="margin-left: 15px;" />
<datalist id="assenza">
<option value="Normali">
<option value="Straordinarie">
<option value="Ferie">
<option value="Malattia">
<option value="Permesso">
<option value="Smart Working">
<option value="Altro">
</datalist>
<input type="hidden" name="nomeUtente" id="nomeUtente" value="<?php echo $_SESSION["nomeUtente"]; ?>">
</div>
<div class="form-group row">
<label class="col-md-2 form-control-label" for="editStarts">Inizio:</label>
<div class="col-md-10">
<div class="input-group">
<input type="datetime-local" class="form-control" id="editStarts" name="editStarts" data-container="#editNewEvent">
</div>
</div>
</div>
<div class="form-group row">
<label class="col-md-2 form-control-label" for="editEnds">Fine:</label>
<div class="col-md-10">
<div class="input-group">
<input type="datetime-local" class="form-control" id="editEnds" name="editEnds"data-container="#editNewEvent">
</div>
</div>
</div>
</div>
<div class="modal-footer">
<div class="form-actions">
<button class="btn btn-primary" data-dismiss="modal" type="button">Salva modifiche</button>
<a class="btn btn-sm btn-white btn-pure" data-dismiss="modal" href="javascript:void(0)">Annulla</a>
</div>
</div>
</form>
</div>
</div>
<!-- End EditEvent Dialog -->
</div>
</div>
</div>
</body>
</html>
This is the template i'm using it, most of the code it's there, i just update the part i'm using and modifing
Since you're already using jQuery, you can use it to access the elements instead of native js
Here $(this).prop('checked') is being used to check the checked property of the checkbox
Then when it changes, change the visibility of the element based on the current state..
NOTE: The checkbox is checked initially because the element to toggle is visible when the document loads
$(function() {
$('input[type="checkbox"]').on('change', function() {
x = $('.fc-event-container')
// Access the element using jQuery
if($(this).prop('checked')){
x.css({
'visibility': 'visible'
})
}
else {
x.css({
'visibility': 'hidden'
})
}
})
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="fc-event-container">
Toggle the checkbox to toggle me
</div>
<input type="checkbox" id="OP" name="calendario" value="OP" checked>
One thing to note about the calendar is that every time you switch the month, week or day, the events are rendered again..
So that means the events will have their default state which is visible every time you switch through the tabs
So if you want to ensure the element remains hidden you have to access the element only after it has been rendered, because rendering happens sequentially, so you cannot access the element as soon as rendering has started, because by then you can't know when it will render..
So the concept I've introduced is just using the property of the calendar which is dayRender to check when the rendering of the contents is being done, and set a timeout of half a second to return the events back to their initial state..
So that is the concept, you can read through the docs to find an event that will fire after all the rendering of the days is done and then call the function to revert back them to their visible or hidden state
Check the codepen for the working demo
Use onchange event
$(document).ready(function() {
$('#OP').change(function() {
var x = document.getElementsByClassName("fc-event-container");
if (this.checked){
x.style.visibility = "visible !important";
}else{
x.style.visibility = "hidden !important";
}
})
});

Fullcalender V5 RefetchEvents issue

I am using Fullcalender Scheduler V5.
I added calendar.refetchEvents(); at the end of eventDrop, eventResize, eventClick also. It is working well. But when I use it in other functions to add /edit the events, it is not working.Here is my code:
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8' />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
<script src='moment-timezone.js'></script>
<script src='lib/locales-all.js'></script>
<link href='fullcalender_scheduler/main.css' rel='stylesheet' />
<script src='fullcalender_scheduler/main.js'></script>
<script src='fullcalender_scheduler/ja.js'></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
<script>
document.addEventListener('DOMContentLoaded', function() {
var calendarEl = document.getElementById('calendar');
var calendar = new FullCalendar.Calendar(calendarEl, {
schedulerLicenseKey: 'GPL-My-Project-Is-Open-Source',
eventTimeFormat: { hour: 'numeric', minute: '2-digit' },
businessHours: true,
height: '100%',
aspectRatio: 1.8,
editable: true, // enable draggable events
now: new Date(),
scrollTime: '00:00', // undo default 6am scrollTime
headerToolbar: {
left: 'today prev,next',
center: 'title',
right: 'resourceTimelineDay,resourceTimelineTenDays,timeGridWeek,dayGridMonth,listWeek'
},
initialView: 'resourceTimelineDay',
views: {
resourceTimelineTenDays: {
type: 'resourceTimeline',
duration: { days: 10 },
buttonText: '10 days'
}
},
expandRows: true,
resourceAreaWidth: '10%',
resourceAreaHeaderContent: 'Rooms',
resourceOrder: 'type1', // to set the displayorder of resources
resources: [
{ id: '1', title: 'R1' , eventColor: 'blue', type1:10},
{ id: '2', title: 'R2', eventColor: 'green',type1:13 },
{ id: '3', title: 'R3', eventColor: '#F39C12',type1:14 },
{ id: '4', title: 'R4', eventColor: 'red' ,type1:11 },
{ id: '5', title: 'R5', eventColor: '#8E44AD',type1:12 },
],
events :'load.php',
selectable:true,
selectHelper:true,
//---------------------------ADD EVENTS----------------------------------------///
select: function(info) {
var st_time = info.startStr;
var start =st_time.split("T").join(" ");
var end_time = info.endStr;
var end =end_time.split("T").join(" ");
var resourc =info.event._def.resourceIds;
var resourceId = resourc.toString();
$('#ModalAdd').modal('show');
$('#ModalAdd #Room').val(resourceId);
$('#ModalAdd #start').val(start);
$('#ModalAdd #end').val(end);
},
eventResize:function(info)
{
var resourc =info.event._def.resourceIds;
var resourceId = resourc.toString();
var title = info.event.title;
var start =info.event.start;
var end =info.event.end;
var id = info.event.id;
var scriptUrl = "DragEvent.php";
$.ajax({
url:scriptUrl,
type:"POST",
data:{title:title, start:start, end:end, id:id, resourceId:resourceId},
success: function(data){
alert('Event updated');
calendar.refetchEvents();---------Here, its working well
}
})
},
});
calendar.render();
});
function saveData()
{
var Room= document.getElementById("Room").value;
var EventName= document.getElementById("EventName").value;
var start=document.getElementById("start").value;
var end=document.getElementById("end").value;
var ScriptUrl="addEvent.php";
$.ajax({
url:ScriptUrl,
type:"POST",
data:{EventName:EventName, start:start, end:end},
success: function(data){
alert("Added successfully");
// calendar.refetchEvents();-----------------------tried here. Not working
}
});
$('#ModalAdd').modal('hide');
calendar.refetchEvents();----------Here also, Not working
}
</script>
<style>
html, body {
overflow: hidden; /* don't do scrollbars */
font-family: Arial, Helvetica Neue, Helvetica, sans-serif;
font-size: 14px;
}
#calendar-container {
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0;
}
.fc-header-toolbar {
padding-top: 1em;
padding-left: 1em;
padding-right: 1em;
}
</style>
</head>
<body>
<!-- Modal -->
<div class="modal fade" id="ModalAdd" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<form class="form-horizontal" method="POST" action="pages/calenderpages/addEvent.php" name="add_item" id ="add_item">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel"><b>Add events</b></h4>
</div>
<div class="modal-body">
<div class="form-group">
<input type="hidden" name="Room" class="form-control" id="Room" value="">
<label for="genryo" class="col-sm-4 control-label">Event name</label>
<div class="col-sm-8">
<input type="text" name="EventName" class="form-control" id="EventName" value="">
</div>
</div>
<div class="form-group">
<label for="start" class="col-sm-4 control-label">Start</label>
<div class="col-sm-8">
<input type="text" name="start" class="form-control" id="start" readonly>
</div>
</div>
<div class="form-group">
<label for="end" class="col-sm-4 control-label">End</label>
<div class="col-sm-8">
<input type="text" name="end" class="form-control" id="end" readonly>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">CLOSE</button>
<button type="button" class="btn btn-primary" onclick="saveData()">SAVE</button>
</div>
</form>
</div>
</div>
</div>
<!------------------------------------------>
<div id='calendar-container'>
<div id='calendar'></div>
</div>
</body>
</html>
Here is my other codes:
/-----------------------Load.php------------------------------//
<?php
require_once('../../common/conn_check.php');
require_once('../../common/common.php');
$data=array();
$query ="SELECT * FROM event_schedule ";
$statement = pg_query($conn,$query);
$result = pg_fetch_all($statement);
foreach($result as $row)
{
$data[] = array(
'id' => $row["id"],
'resourceId' => $row["Room"],
'title' =>$row["EventName"],
'start' => $row["StartTime"],
'end' => $row["EndTime"]
);
}
echo json_encode($data);
?>
/---------------AddEvents.php-------------------//
<?php
require_once('../../common/conn_check.php');//for using the mysql connection
require_once('../../common/common.php');//common function
if (isset($_POST['start']) && isset($_POST['end'])){
$EventName = $_POST['EventName'];
$Room = $_POST['Room'];
$start = $_POST['start'];
$end = $_POST['end'];
$sql="INSERT INTO event_schedule
(Room,EventName, StartTime,EndTime)
VALUES
('$EventName','$Room','$start', '$end')";
$result = pg_query($conn,$sql);
echo json_encode(array('success'=>true));
}
?>
I have been trying this for weeks, I lost my confidence due to this. As a beginner, I couldn't figure out what's going wrong. Someone, please help.
The simplest option here is to make calendar global so it's accessible in all scopes.
e.g.
<script>
var calendar; //global variable
document.addEventListener('DOMContentLoaded', function() {
var calendarEl = document.getElementById('calendar');
calendar = new FullCalendar.Calendar(calendarEl, { //don't re-declare it here, just assign it
///...etc
But global variables are usually not best practice - it can lead to other issues if you're not careful. So another option is to stop using an inline event handler to trigger saveData, and instead add an event handler inside the DOMContentLoaded block, where of course calendar is already in scope. You make saveData return a Promise from the AJAX call, and then in the event handler you attach a .done() callback to it, and in there you can call refetchEvents.
So in this version, your button would become
<button type="button" class="btn btn-primary" id="savedata">SAVE</button>
and saveData() would become:
function saveData()
{
var Room = document.getElementById("Room").value;
var EventName = document.getElementById("EventName").value;
var start = document.getElementById("start").value;
var end = document.getElementById("end").value;
var promise = $.ajax({
url: "addEvent.php",
type:"POST",
data:{ EventName: EventName, start:start, end: end },
});
$('#ModalAdd').modal('hide');
return promise;
}
And lastly in the DOMContentLoaded area:
document.addEventListener('DOMContentLoaded', function() {
//....everything which is already there....and then...
$("#savedata").click(function() {
var promise = saveData();
promise.done(function(data) {
calendar.refetchEvents();
});
});
});
Although it looks like more work, this is a much better structured version than using a global variable.

How to take boostrap modal inputs to insert to SQL table using AJAX through fullcalendar

I have been trying for some time to get this working. I am struggling to take user input from a modal and insert it into a my database in phpmyadmin. Any help would be greatly appreciated.
1) Using the select callback I bring up a modal:
select: function(start, end, allDay)
{
$('#myModal').modal('show');
},
2) The modal itself in the HTML:
<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Add Event</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<form>
<div class="form-group">
<label for="FormControlInput1">Task Title</label>
<input type="text" class="form-control" id="title" placeholder="Enter Task Title">
</div>
<div class="form-group">
<label for="FormControlInput2">Task Number</label>
<input type="text" class="form-control" id="number" placeholder="Enter Task Number>
</div>
<div class="form-group">
<label for="FormControlInput3">Location</label>
<input type="text" class="form-control" id="location" placeholder="Enter Location">
</div>
<div class="form-group">
<label for="FormControlTextarea1">Tooling Required</label>
<textarea class="form-control" id="tooling" placeholder="Enter the tools required for the task here" rows="3"></textarea>
</div>
<div class="form-group">
<label for="FormControlTextarea2">Consumables</label>
<textarea class="form-control" id="consumables" placeholder="Enter the consumables required for the task here" rows="3"></textarea>
</div>
<div class="form-group">
<label for="FormControlSelect1">Safety Condition</label>
<select class="form-control" id="safety">
<option>0</option>
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
</select>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary" id="buttonAddEvent">Add Event</button>
</div>
</div>
</div>
</div>
3) At this point I would like to use my insert.php file I have made, which works for other functions in the code:
<?php
//insert.php
$connect = new PDO('mysql:host=hostname;dbname=dbname', 'username', 'password');
if(isset($_POST["title"]))
{
$query = "
INSERT INTO events
(title, number, location, tooling, consumables, safety, start_event, end_event)
VALUES (:title, :number, :location, :tooling, :consumables, :safety, :start_event, :end_event)
";
$statement = $connect->prepare($query);
$statement->execute(
array(
':title' => $_POST['title'],
':number' => $_POST['number'],
':location' => $_POST['location'],
':tooling' => $_POST['tooling'],
':consumables' => $_POST['consumables'],
':safety' => $_POST['safety'],
':start_event' => $_POST['start'],
':end_event' => $_POST['end']
)
);
}
?>
I have typically inserted data using the following code however this uses prompts() which I want to replace with the modal inputs:
select: function(start, end, allDay)
{
var title = prompt("Enter Task Title");
if(title)
{
var number = prompt("Enter Task Number");
var location = prompt("Enter Train Location");
var tooling = prompt("Enter Tooling Required");
var consumables = prompt("Enter Consumables Required");
var start = $.fullCalendar.formatDate(start, "Y-MM-DD HH:mm:ss");
var end = $.fullCalendar.formatDate(end, "Y-MM-DD HH:mm:ss");
$.ajax({
url:"insert.php",
type:"POST",
data:{title:title, number:number, location:location, tooling:tooling, consumables:consumables, start:start, end:end},
success:function()
{
calendar.fullCalendar('refetchEvents');
}
})
}
},
Needed to make use of .on() to pass data from modal input to variables
select: function(start, end, allDay)
{
var start = $.fullCalendar.formatDate(start, "Y-MM-DD HH:mm:ss");
var end = $.fullCalendar.formatDate(end, "Y-MM-DD HH:mm:ss");
$('#myModal').modal('show')
$('#buttonAddEvent').on('click', function (){
var title = $("#myModal #title").val().trim();
var number = $("#myModal #number").val().trim();
var location = $("#myModal #location").val().trim();
var tooling = $("#myModal #tooling").val().trim();
var consumables = $("#myModal #consumables").val().trim();
var safety = $("#myModal #safety").val().trim();
var mockEvent = {title:title, number:number, location:location, tooling:tooling, consumables:consumables, safety:safety, start:start, end:end};
$('#calendar').fullCalendar('renderEvent', mockEvent);
$('#buttonAddEvent').unbind('click');
$('#myModal').modal('hide');
$.ajax({
url:"insert.php",
type:"POST",
data:{title:title, number:number, location:location, tooling:tooling, consumables:consumables, safety:safety, start:start, end:end},
success:function()
{
calendar.fullCalendar('refetchEvents');
}
});
});
},
Thanks to #ADyson for pointing in the right direction.
i 'm not seeing any return data from your php code (which is generally get newly updated record and returns as json_encode),
and then the Ajax Success Function should process the response data and fetch it to calendar

Bootstrap Datepicker some options are not seems to be working

I have 2 datepickers which use bootstrap and knockout to bind data.
The below is my html template for datepickers and I have added the options
<div class="clearfix form-inline marginBottom10px row col-md-12 fontWeightNormal" role="form">
<span class="col-md-2 col-xs-12 pull-left paddingLeft0px">
<label class="control-label paddingTop5px" for="datespanFromfilter">
From
</label>
</span>
<div class="form-group col-md-3 paddingLeft0px paddingRight0px">
<span class="date input-group" id="datespanFromfilter" data-date-format="DD/MM/YYYY" data-bind="datetimepicker :dateSpanFrom, datePickerOptions : {todayBtn : true, pickTime: false, format: 'DD/MM/YYYY', maxDate : new Date(), orientation: 'left'}, enable: !refreshingPage()">
<input class="form-control" id="datespanFromfilterinput" placeholder="DD/MM/YYYY" data-bind="value: dateSpanFrom, enable: !refreshingPage()" disabled />
<span class="input-group-addon" data-bind="enable: !refreshingPage()">
<span class="glyphicon glyphicon-calendar" data-bind="enable: !refreshingPage()"></span>
</span>
</span>
</div>
<div class="col-md-1 ">
<label class="control-label paddingLeft0px paddingTop5px" for="datespanTofilter">
To
</label>
</div>
<div class="form-group col-md-3 paddingLeft0px paddingRight0px">
<span class="date input-group" id="datespanTofilter" data-date-format="DD/MM/YYYY" data-bind="datetimepicker : dateSpanTo, datePickerOptions : {todayBtn : true, pickTime: false, orientation: 'left', format : 'DD/MM/YYYY', maxDate : new Date()}, enable: !refreshingPage()">
<input class="form-control" placeholder="DD/MM/YYYY" data-bind="value: dateSpanTo, enable: !refreshingPage()" disabled />
<span class="input-group-addon" data-bind="enable: !refreshingPage(), disabled: !refreshingPage()">
<span class="glyphicon glyphicon-calendar" data-bind="enable: !refreshingPage()"></span>
</span>
</span>
</div>
</div>
This is how I handle the Datepicker in knockout
ko.bindingHandlers.datetimepicker = {
/// <summary>The customized event handler datepicker.</summary>
init: function (element, valueAccessor, allBindingsAccessor) {
allBindings = allBindingsAccessor();
var options = allBindings.datePickerOptions || {};
ko.utils.extend(options, allBindings.datePickerOptions)
$(element).datetimepicker(options).on("change.dp", function (evntObj) {
self.errorMessage("");
var observable = valueAccessor();
if (evntObj.timeStamp !== undefined) {
var picker = $(this).data("DateTimePicker");
var d = picker.getDate();
if (d != null && d != '') {
observable(d.format(picker.format));
}
else {
observable(moment(settings.defaultUtcDate).format("DD/MM/YYYY"));
}
}
});
},
update: function (element, valueAccessor) {
self.errorMessage("");
var thisFormat = 'DD/MM/YYYY';
var value = ko.utils.unwrapObservable(valueAccessor());
$(element).data("DateTimePicker").setDate(moment(value).format(thisFormat));
}
};
but in options only Format and pickTime seems to be working fine, I also need to show TodayButton and correct the orientation.
But these to options are not working if i change the value
Will someone help me to solve the issue

How do I get the modal window to pop up when I select a time slot on fullCalendar?

I have been able to get my FullCalendar plug in working on my local host and want to be able to create events through a pop up window. The following code sets up the calendar and allows me to select a time slot and I thought present the modal view to allow an entry to be made:
$(document).ready(function(){
var calendar = $('#calendar').fullCalendar({
header:
{
left: 'prev,next today',
center: 'title',
right: 'agendaDay agendaWeek month'
},
defaultView: 'agendaWeek',
slotDuration : '00:15:00',
scrollTime: '13:00:00',
minTime : '09:00:00',
maxTime : '21:00:00',
slotEventOverlap: false,
firstDay : 1,
selectable: true,
selectHelper: true,
editable:true,
//select function:
select: function(start, end, allDay){
endtime = $.fullCalendar.formatDate(end, 'h:mm tt');
starttime = $.fullCalendar.formatDate(start, 'ddd, MMM d, h:mm tt');
var mywhen = starttime + ' - ' + endtime;
$('#createEventModal #apptStartTime').val(start);
$('#createEventModal #apptEndTime').val(end);
$('#createEventModal #apptAllDay').val(allDay);
$('#createEventModal #when').text(mywhen);
$('#createEventModal').modal('show');
},
});
//function to submit the form
$('#submitButton').on('click', function(e){
//cancel the link options
e.preventDefault();
doSubmit();
});
});
function doSubmit(){
alert("form submitted");
$("#createEventModal").modal('hide');
$("#calendar").fullCalendar('renderEvent',
{
title: $('#clientName').val(),
start: new Date($('#apptStartTime').val()),
end: new Date($('#apptEndTime').val()),
allDay: ($('#apptAllDay').val() == "true"),
},
true);
}
this is my HTML code as it stands to create my modal form:
<!--call the calendar -->
<div id='calendar'></div>
<!-- form to capture appointment Data-->
<div id="createEventModal" class="modal hide" tabindex="-1" role="dialog" aria-labelledby="myModalLabel1" aria-hidden="true">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">x</button>
<h3 id="myModalLabel1">Book Appointment</h3>
</div>
<div class="modal-body">
<form id="createAppointmentForm" class="form-horizontal">
<div class="control-group">
<label class="control-label" for="inputClient">Client:</label>
<div class="controls">
<input type="text" name="clientName" id="clientName" placeholder="name here"
tyle="margin: 0 auto;" data-provide="typeahead" data-items="4" data-source="[
"Value 1","Value 2","Value 3"]">
<input type="hidden" id="apptStartTime"/>
<input type="hidden" id="apptEndTime"/>
<input type="hidden" id="apptAllDay"/>
</div>
</div>
<div class="control-group">
<label class="control-label" for="when">When:</label>
<div class="controls controls-row" id="when" style="margin-top:5px;">
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" data-dismiss="modal" aria-hidden="true" class="btn">Cancel</button>
<button type="submit" id="submitButton" class="btn btn-primary">Save Appointment</button>
</div>
</div>
I don't know what I am missing to get the form to present to user. I am new to web development and would really appreciate some help with this
Try using the jQuery UI Dialog widget. For what you want, you might need some code like the following.
$(".modal-body").dialog({
title: "Book Appointment",
modal: true,
buttons: {
"Save Appointment": function() {
//appt save code here
},
Cancel: function() {
$(this).dialog("close");
}
}
});

Categories