FullCalendar open bootstrap modal on eventClick - javascript

I have a bootstrap fullcalendar, when I click on an empty day, the modal which allows to save the events is displayed well, but when I click on an event to modify it, the modal which allows to modify the event, does't display.
I have a bootstrap fullcalendar, when I click on an empty day, the modal which allows to save the events is displayed well, but when I click on an event to modify it, the modal which allows to modify the event, does't display.
I don't know where the problem comes from
this is my code :
<div class="modal fade" id="PrestUpt" role="dialog" class="modal fade task-modal-single in" tabindex="-1" aria-labelledby="myLargeModalLabel" >
<div class="modal-dialog modal-lg">
<div class="modal-content data">
<div id="jalil" ></div>
</div>
</div>
</div>
<script>
$(document).ready(function() {
// jQuery("#PrestUpt").modal('show');
var calendar = $('#calendar').fullCalendar({
locale: 'fr',
plugins: [ 'bootstrap', 'interaction', 'dayGrid', 'timeGrid' ],
firstDay: 1,
editable:true,
header:{
left:'prev,next today',
center:'title',
right:'month,agendaWeek,agendaDay'
},
events: 'event_load_new.php',
selectable:true,
selectHelper:true,
select: function (start, end, allDay) {
//do something when space selected
//Show 'add event' modal
// var start = $.fullCalendar.formatDate(event.start, "Y-MM-DD HH:mm:ss");
var start = $.fullCalendar.formatDate(start, "Y-MM-DD");
document.getElementById('start').value = start;
$('#exampleModal').modal('show');
},
editable:true,
eventResize:function(event)
{
var start = $.fullCalendar.formatDate(event.start, "Y-MM-DD HH:mm:ss");
var end = $.fullCalendar.formatDate(event.end, "Y-MM-DD HH:mm:ss");
var title = event.title;
var id = event.id;
$.ajax({
url:"event_update.php",
type:"POST",
data:{title:title, start:start, end:end, id:id},
success:function(){
calendar.fullCalendar('refetchEvents');
alert("Mise à jour de l'événement");
}
})
},
eventClick: function(info) {
var idpr = info.event.id;
alert(idpr);
// datepr = datepr.substr(6, 4)+ '' +datepr.substr(3, 2)+ '' +datepr.substr(0, 2);
$.ajax({
type : 'post',
url : 'moadal_gool.php', //Here you will fetch records
data : 'idp='+idpr, //Pass $id
success : function(data){
$('#jalil').html(data);//Show fetched data from database
jQuery("#PrestUpt").modal('show');
}
});
},
eventDrop:function(event)
{
var start = $.fullCalendar.formatDate(event.start, "Y-MM-DD HH:mm:ss");
var end = $.fullCalendar.formatDate(event.end, "Y-MM-DD HH:mm:ss");
var title = event.title;
var id = event.id;
$.ajax({
url:"event_update.php",
type:"POST",
data:{title:title, start:start, end:end, id:id},
success:function()
{
calendar.fullCalendar('refetchEvents');
alert("Événement mis à jour");
}
});
},
});
});
</script>

This is how you do it...
eventClick: this.openModal.bind(this)
//then create a function openModal()
openModal(args:any){
jQuery("#PrestUpt").modal("show");
...
}

Related

How to update database after cloning an event in fullcalendar using AJAX

I'm relatively new to programming and some help would be greatly appreciated.
I am using fullcalendar and have got it to the point where I can add, remove & drag and drop events. My last requirement is to be able to clone events for quicker management.
I am using the following code to clone events (taken from a previous post). Currently this does not save to the database:
eventClick: function (event, jsEvent, ui, view) {
if (!copyKey) return;
var eClone = {
id: event.id+1,
title: event.title,
tooling: event.tooling,
start: event.start,
end: event.end
};
$('#calendar').fullCalendar('renderEvent', eClone);
},
An example piece of code I have used to update my SQL database is here:
eventDrop:function(event)
{
var start = $.fullCalendar.formatDate(event.start, "Y-MM-DD HH:mm:ss");
var end = $.fullCalendar.formatDate(event.end, "Y-MM-DD HH:mm:ss");
var title = event.title;
var tooling = event.tooling;
var id = event.id;
$.ajax({
url:"update.php",
type:"POST",
data:{title:title, tooling:tooling, start:start, end:end, id:id},
success:function()
{
calendar.fullCalendar('refetchEvents');
}
});
},
My main confusion is how to use AJAX for my clone function, also making sure to increment the id when a new event is created.
Had to make use of insert.php rather than update.php...
Final working code:
eventClick: function (event, jsEvent, ui, view)
{
if (!copyKey) return;
var eClone = {
id: event.id,
title: event.title,
tooling: event.tooling,
start: event.start,
end: event.end
};
$('#calendar').fullCalendar('renderEvent', eClone);
var start = $.fullCalendar.formatDate(event.start, "Y-MM-DD HH:mm:ss");
var end = $.fullCalendar.formatDate(event.end, "Y-MM-DD HH:mm:ss");
var title = event.title;
var tooling = event.tooling;
var id = event.id;
$.ajax({
url:"insert.php",
type:"POST",
data:{title:title, tooling:tooling, start:start, end:end, id:id},
success:function()
{
$('#calendar').fullCalendar('renderEvent', eClone);
calendar.fullCalendar('refetchEvents');
}
});
},

show same month/week/day upon refresh of fullcalendar

I am using a fullcalendar plugin to display various events.
My problem is when I change the month/week being viewed, then refresh, I get taken back to the current month/week, when I want to stay on the same month/week I was viewing beforehand. i.e. If it's August right now, and I go back to July, then refresh, I want the page to display the calendar for July and not August.
Code that gives a working calendar for the problem specified is given below. Note that I understand this calendar doesn't fully work (can't add events etc.), but it saving it as index.html and opening it will show the problem I have of not opening at the previous view after a refresh.
<!DOCTYPE html>
<html>
<head>
<title>Jquery Fullcalandar Integration with PHP and Mysql</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/fullcalendar/3.4.0/fullcalendar.css" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-alpha.6/css/bootstrap.css" />
<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="https://cdnjs.cloudflare.com/ajax/libs/fullcalendar/3.4.0/fullcalendar.min.js"></script>
<script>
$(document).ready(function() {
var calendar = $('#calendar').fullCalendar({
allDaySlot: false,
editable:true,
header:{
left:'prev,next today',
center:'title',
right:'month,agendaWeek,agendaDay'
},
events: [{"id":1,"title":"one","start":"2019-08-11 00:00:00","end":"2019-08-12 00:00:00", 'color': 'Fuchsia'}],
selectable:true,
selectHelper:true,
select: function(start, end, allDay)
{
var title = prompt("Enter Event Title");
if(title)
{
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, start:start, end:end},
success:function()
{
calendar.fullCalendar('refetchEvents');
alert("Added Successfully");
}
})
}
},
editable:true,
eventResize:function(event)
{
var start = $.fullCalendar.formatDate(event.start, "Y-MM-DD HH:mm:ss");
var end = $.fullCalendar.formatDate(event.end, "Y-MM-DD HH:mm:ss");
var title = event.title;
var id = event.id;
$.ajax({
url:"update.php",
type:"POST",
data:{title:title, start:start, end:end, id:id},
success:function(){
calendar.fullCalendar('refetchEvents');
alert('Event Update');
}
})
},
eventDrop:function(event)
{
var start = $.fullCalendar.formatDate(event.start, "Y-MM-DD HH:mm:ss");
var end = $.fullCalendar.formatDate(event.end, "Y-MM-DD HH:mm:ss");
var title = event.title;
var id = event.id;
$.ajax({
url:"update.php",
type:"POST",
data:{title:title, start:start, end:end, id:id},
success:function()
{
calendar.fullCalendar('refetchEvents');
alert("Event Updated");
}
});
},
eventClick:function(event)
{
if(confirm("Are you sure you want to remove it?"))
{
var id = event.id;
$.ajax({
url:"delete.php",
type:"POST",
data:{id:id},
success:function()
{
calendar.fullCalendar('refetchEvents');
alert("Event Removed");
}
})
}
},
});
});
</script>
</head>
<body>
<br />
<h2 align="center">Jquery Fullcalandar Integration with PHP and Mysql</h2>
<br />
<div class="container">
<div id="calendar"></div>
</div>
</body>
</html>
I wish to add a property somewhere (presumably after line 14 var calendar = $('#calendar').fullCalendar({ ) that makes it so after a refresh, I end up on the month/week I was previously on.
You can add this code to solve your problem
$(document).on('click', '.fc-next-button,.fc-prev-button', function () {
localStorage.setItem('savedMonth',$('#calendar').fullCalendar('getView').intervalStart._d);
});
if(localStorage.getItem('savedMonth')!=null){
$('#calendar').fullCalendar('gotoDate',localStorage.getItem('savedMonth'));
}
or you can do this using cookies instead of local storage

Return Data with EventClick Full Calendar

Good afternoon guys, I need a help, I'm using Fullcalendar to create a simple calendar, I can already create events save them in the DB and display them in the calendar, now what I need is that when clicking on the event a popup ( Modal) is opened displaying the data of the event and also the option to perform an update of this data, I am already with the modal working when clicking on the event it is opened what I do not know is how to display the data saved in the BD in their respective fields Here are my codes:
Controler(calendar2.php):
class Calendar2 extends CI_controller{
function __construct(){
parent:: __construct();
$this->load->model('calendar2Model', 'model', TRUE);
}
public function index(){
$this->template->set('title', 'Agenda');
$this->template->load('layout', 'calendar_v.php');
//$this->load->view('calendar_v.php');
}
public function getEvents(){
$data = $this->model->get_events();
echo json_encode($data);
}
public function updateEvents(){
$param['id'] = $this->input->post('id');
$param['inicio'] = $this->input->post('inicio');
$param['fim'] = $this->input->post('fim');
$r = $this->model->updateEvents($param);
echo json_encode($r);
}
public function deleteEvents(){
$id = $this->input->post('id');
$r = $this->model->deleteEvents($id);
echo json_encode($r);
}
public function new_event(){
$this->template->set('title', 'Nova tarefa');
$this->load->library('form_validation');
/* Define as tags onde a mensagem de erro será exibida na página */
$this->form_validation->set_error_delimiters('<span>', '</span>');
/* Define as regras para validação */
$this->form_validation->set_rules('nomeEvento', 'Nome', 'required|max_length[40]');
$this->form_validation->set_rules('inicio', 'Data de inicio', 'trim|required|max_length[60]');
$this->form_validation->set_rules('importancia', 'Prioridade', 'trim|required|max_length[60]');
$this->form_validation->set_rules('descricaoEvento', 'descricaoEvento', 'trim|required|max_length[150]');
/* Executa a validação e caso houver erro chama a função index do controlador */
if ($this->form_validation->run() === FALSE) {
$this->template->load('layout', 'clientes_inserir.phtml');
/* Senão, caso sucesso: */
} else {
/* Recebe os dados do formulário (visão) */
$data['nomeEvento'] = $this->input->post('nomeEvento');
$data['inicio'] = $this->input->post('inicio');
$data['fim'] = date('Y-m-d', strtotime($this->input->post('inicio'). ' + 1 day'));
$data['user'] = $this->input->post('user');
$data['importancia'] = $this->input->post('importancia');
$data['importancia'] = $this->input->post('descricaoEvento');
/* Chama a função inserir do modelo */
if ($this->model->inserir($data)) {
$this->session->set_flashdata('mensagem', 'registro salvo com sucesso');
redirect('clientes');
} else {
$this->session->set_flashdata('mensagem', 'registro nao salvo');
}
}
}
}
Modal(calendar2model.php):
<?php
class calendar2Model extends CI_Model {
function __construct() {
parent::__construct();
}
public function get_events(){
$this->db->select('idevento id,cnome title, inicio start, fim end');
$this->db->from('eventos');
$this->db->join('clientes','clientes.ccod = eventos.nomeEvento');
return $this->db->get()->result();
}
function inserir($data) {
return $this->db->insert('eventos', $data);
}
function updateEvents($param) {
$campos = array(
'inicio' => $param['inicio'],
'fim' => $param['fim']
);
$this->db->where('idevento', $param['id']);
$this->db->update('eventos', $campos);
if($this->db->affected_rows() == 1){
return 1;
} else{
return 0;
}
}
function deleteEvents($id){
$this->db->where('idevento', $id);
$this->db->delete('eventos');
if($this->db->affected_rows() == 1){
return 1;
} else{
return 0;
}
}
}
View(calendar_v.php):
<head>
<div class="row" >
<div class="col-sm-2">
<a data-toggle="modal" data-target="#new_event" class="btn btn-primary">Nova Tarefa</a>
</div>
</div>
<script>
$(document).ready(function() {
$.post('<?php echo base_url();?>calendar2/getEvents',
function(data){
//alert(data);
$('#calendar').fullCalendar({
header: {
left: 'prev,next today',
center: 'title',
right: 'month,basicWeek,basicDay'
},
defaultDate: new Date(),
navLinks: true, // can click day/week names to navigate views
editable: true,
eventLimit: true, // allow "more" link when too many events
editable: true,
events: $.parseJSON(data),
eventDrop: function(event, delta, revertFunc){
var id = event.id;
var fi = event.start.format();
var ff = event.end.format();
$.post("<?php echo base_url();?>calendar2/updateEvents",
{
id:id,
inicio:fi,
fim:ff,
},
function(data){
if(data == 1){
alert('Evento atualizado');
}else{
alert('Evento Nao atualizado')
}
});
},
eventResize: function(event, delta, revertFunc) {
var id = event.id;
var fi = event.start.format();
var ff = event.end.format();
$.post("<?php echo base_url();?>calendar2/updateEvents",
{
id:id,
inicio:fi,
fim:ff,
},
function(data){
if(data == 1){
//alert('Evento atualizado');
}else{
// alert('Evento não atualizado')
}
});
},
// eventClick: function(event,jsEvent, view){
// $('#calendar').fullCalendar('removeEvents',event.id);
// }
eventRender: function(event, element){
var el = element.html();
element.html("<div style='width:90%;float:left;'>" + el + "</div><div class='closeee' style='color:red; text-align:right;'>X</div>");
element.find('.closeee').click(function(){
if(!confirm("Excluir registro ??")){
revertFunc();
}else{
var id = event.id
$.post("<?php echo base_url();?>calendar2/deleteEvents",
{
id:id,
},
function(data){
if(data == 1){
$('#calendar').fullCalendar('deleteEvents', event.id);
//alert('Tarefa Excluida');
}else{
//alert('Tarefa não Excluida')
}
});
}
});
},
eventClick: function(event, jsEvent, view){
$('#mtitulo').html(event.title);
$('#autor').val(event.id);
$('#modalEvento').modal();
},
});
});
});
</script>
</head>
<body>
<div id='calendar'></div>
</body>
<!-- Modal visualizar-->
<div class="modal fade" id="modalEvento" tabindex="-1" role="dialog" aria-labelledby="mymodelLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header bg-red">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="mymodelLabel"> Editar Evento</h4>
</div>
<div class="modal-body">
<div class="row">
<div class="form-group col-md-6">
<label for="nomeEvento">Nome Cliente</label>
<div class="form-control" id="mtitulo"></div>
</div>
<div class="form-group col-md-6">
<label for="user">Responsavel</label>
<div class="form-control" id="autor"></div>
</div>
</div>
<div class="row">
<div class="form-group col-md-6">
<div class="input-group date">
<input type="text" class="form-control date" id="inicio" name="inicio"/>
<div class="input-group-addon">
<span class="glyphicon glyphicon-th"></span>
</div>
</div>
</div>
<div class="form-group col-md-6">
<label for="importancia">Prioridade</label>
<input type="text" class="form-control" id="importancia" name="importancia"/>
</div>
</div>
<div class="row">
<div class="form-group col-md-12">
<label for="descricaoEvento">Descrição</label>
<input type="text" class="form-control" id="descricaoEvento" name="descricaoEvento"/>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" id="closeM" data-dismiss="modal">Cancelar</button>
<button type="button" class="btn btn-danger" id="btnGuardar">Guardar</button>
</div>
</div>
</div>
</div>
<!-- /.modal -->
You could add an eventRender and attach an onClick listener like follow:
$('#calendar').fullCalendar({
header: {
left: 'prev,next today',
center: 'title',
right: 'month,basicWeek,basicDay'
},
[cut]
eventRender: function (event, element, view) {
element.attr('href', 'javascript:void(0);');
element.click(function() {
$.get( "yoururl/" + event.id, function( data ) {
//Clone object in order to not update the original event (if user press cancel)
var eventClone = deepClone(event);
eventClone.start = data.myStart;
eventClone.end = data.myEnd;
eventClone.title = data.myTitle;
openDialog(eventClone);
});
});
}
[cut]
});
function openDialog(event){
$('#myForm').modal('show');
$('#myModalLabel').html(event.title);
$('#myId').val(event.id);
[cut]
}
So, on you save button (in modal dialog) you could send data to server, save to db and then refresh the calendar like:
$('#calendar').fullCalendar( 'refetchEvents' );
I hope it was clear, bye.
You can add this code:
var calendar = $('#calendar').fullCalendar({
buttonText: {
prev: '<i class="icon-chevron-left"></i>',
next: '<i class="icon-chevron-right"></i>'
},
header: {
left: 'prev,next today',
center: 'title',
right: 'month,agendaWeek,agendaDay'
},
events: jQuery.parseJSON(data),
disableDragging: true,
editable: true,
droppable: true, // this allows things to be dropped onto the calendar !!!
drop: function(date, allDay) { // this function is called when something is dropped
// retrieve the dropped element's stored Event Object
var originalEventObject = $(this).data('eventObject');
var $extraEventClass = $(this).attr('data-class');
// we need to copy it, so that multiple events don't have a reference to the same object
var copiedEventObject = $.extend({}, originalEventObject);
// assign it the date that was reported
copiedEventObject.start = date;
copiedEventObject.allDay = allDay;
if($extraEventClass) copiedEventObject['className'] = [$extraEventClass];
// render the event on the calendar
// the last `true` argument determines if the event "sticks" (http://arshaw.com/fullcalendar/docs/event_rendering/renderEvent/)
$('#calendar').fullCalendar('renderEvent', copiedEventObject, true);
// is the "remove after drop" checkbox checked?
if ($('#drop-remove').is(':checked')) {
// if so, remove the element from the "Draggable Events" list
$(this).remove();
}
}
,
selectable: true,
selectHelper: true,
select: function(start, end, allDay) {
bootbox.prompt("New Event Title:", function(title) {
if (title !== null) {
calendar.fullCalendar('renderEvent',
{
title: title,
start: start,
end: end,
allDay: allDay
},
true // make the event "stick"
);
}
});
calendar.fullCalendar('unselect');
}
,
eventClick: function(calEvent, jsEvent, view) {
var form = $("<form class='form-inline'><label>Change event name </label></form>");
form.append("<input autocomplete=off type=text value='" + calEvent.title + "' /> ");
form.append("<button type='submit' class='btn btn-small btn-success'><i class='icon-ok'></i> Save</button>");
var div = bootbox.dialog(form,
[
{
"label" : "<i class='icon-trash'></i> Delete Event",
"class" : "btn-small btn-danger",
"callback": function() {
calendar.fullCalendar('removeEvents' , function(ev){
return (ev._id == calEvent._id);
})
}
}
,
{
"label" : "<i class='icon-remove'></i> Close",
"class" : "btn-small"
}
]
,
{
// prompts need a few extra options
"onEscape": function(){div.modal("hide");}
}
);
form.on('submit', function(){
calEvent.title = form.find("input[type=text]").val();
calendar.fullCalendar('updateEvent', calEvent);
div.modal("hide");
return false;
});
}
});
Add bootbox.min.js to open popup window.
I hope it will work for you!

Editing Fullcalendar javascript

I'm editing fullcalendar to adapt it to my needs.
First of all here is the code:
<!----HTML---->
<link href='assets/css/fullcalendar.css' rel='stylesheet' />
<link href='assets/css/fullcalendar.print.css' rel='stylesheet' media='print' />
<script src='assets/js/moment.min.js'></script>
<script src='assets/js/jquery-ui.min.js'></script>
<script src='assets/js/fullcalendar_not_min.js'></script>
<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<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">Scegli Zona di Servizio</h4>
</div>
<div class="modal-body" id="myModalBody">
<div class="form-group">
<label for="sel1">Select list (select one):</label>
<select class="form-control" id="mySelect">
<?php
foreach($zone_servizio_array as $zona){
echo '<option value="'.$zona->getId().'">'.$zona->getNome().'</option>';
}
?>
</select>
</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="save();" data-dismiss="modal">Save changes</button>
</div>
</div>
</div>
</div>
<body>
<div id='wrap'>
<div id='external-events'>
<h4>Agenti</h4>
<?php
foreach ($agenti_array as $agente){
echo '<div class=\'fc-event\'>'.$agente->getNome().' '.$agente->getCognome().'</div>';
}
?>
<p>
<img src="assets/img/trashcan.png" id="trash" alt="">
</p>
</div>
<div id='calendar_buttons' align="left">
<div class="btn-group" role="group" aria-label="..." >
<button type="button" class="btn btn-success"><span class="glyphicon glyphicon-floppy-save" aria-hidden="true"></span> Salva</button>
<button type="button" class="btn btn-danger"><span class="glyphicon glyphicon-refresh" aria-hidden="true"></span> Ripristina</button>
</div>
</div>
<div id='calendar'></div>
<div style='clear:both'></div>
<xspan class="tt">x</xspan>
</div>
</body>
Here is the Javascript:
<script>
var salva = 0; //control variable
function save(){//to change the control variable value
salva = 1;
}
function saveEvent(event, title, start, zone){
$('#myModal').modal('show');
$('#myModal').on('hidden.bs.modal', function (e) {
zona_servizio = document.getElementById('mySelect').value;
if(salva == 1){
console.log('before save event', event, title, start, zone);
$.ajax({
url: 'process.php',
data: 'type=new&title='+title+'&startdate='+start+'&zone='+zone+'&zona_servizio='+zona_servizio,
type: 'POST',
dataType: 'json',
success: function(response){
event.id = response.eventid;
$('#calendar').fullCalendar('updateEvent',event);
},
error: function(e){
console.log(e.responseText);
}
});
}else{
$('#calendar').fullCalendar('removeEvents');
getFreshEvents();
}
});
//$('#calendar').fullCalendar('updateEvent',event);
salva = 0;
console.log('end save event', event);
}
$(document).ready(function() {
zone = "01:00"; //Change this to your timezone
$.ajax({
url: 'process.php',
type: 'POST', // Send post data
data: 'type=fetch',
async: false,
success: function(s){
json_events = s;
}
});
var currentMousePos = {
x: -1,
y: -1
};
jQuery(document).on("mousemove", function (event) {
currentMousePos.x = event.pageX;
currentMousePos.y = event.pageY;
});
/* initialize the external events
-----------------------------------------------------------------*/
$('#external-events .fc-event').each(function() {
// store data so the calendar knows to render an event upon drop
$(this).data('event', {
title: $.trim($(this).text()), // use the element's text as the event title
stick: true // maintain when user navigates (see docs on the renderEvent method)
});
// make the event draggable using jQuery UI
$(this).draggable({
zIndex: 999,
revert: true, // will cause the event to go back to its
revertDuration: 0 // original position after the drag
});
});
/* initialize the calendar
-----------------------------------------------------------------*/
$('#calendar').fullCalendar({
events: JSON.parse(json_events),
//events: [{"id":"14","title":"New Event","start":"2015-01-24T16:00:00+04:00","allDay":false}],
utc: true,
header: {
left: 'prev,next today',
center: 'title',
right: 'month,agendaWeek,agendaDay'
},
editable: true,
droppable: true,
slotDuration: '00:30:00',
**eventReceive**: function(event){
var title = event.title;
var start = event.start.format("YYYY-MM-DD[T]HH:mm:SS");
console.log('event Receive', event, title, start, zone);
saveEvent(event, title, start, zone);
},
eventDrop: function(event, delta, revertFunc) {
var title = event.title;
var start = event.start.format();
var end = (event.end == null) ? start : event.end.format();
$.ajax({
url: 'process.php',
data: 'type=resetdate&title='+title+'&start='+start+'&end='+end+'&eventid='+event.id,
type: 'POST',
dataType: 'json',
success: function(response){
if(response.status != 'success')
revertFunc();
},
error: function(e){
revertFunc();
alert('Error processing your request: '+e.responseText);
}
});
},
eventClick: function(event, jsEvent, view) {
console.log(event.id);
var title = prompt('Event Title:', event.title, { buttons: { Ok: true, Cancel: false} });
if (title){
event.title = title;
console.log('type=changetitle&title='+title+'&eventid='+event.id);
$.ajax({
url: 'process.php',
data: 'type=changetitle&title='+title+'&eventid='+event.id,
type: 'POST',
dataType: 'json',
success: function(response){
if(response.status == 'success')
$('#calendar').fullCalendar('updateEvent',event);
},
error: function(e){
alert('Error processing your request: '+e.responseText);
}
});
}
},
eventResize: function(event, delta, revertFunc) {
console.log(event);
var title = event.title;
var end = event.end.format();
var start = event.start.format();
$.ajax({
url: 'process.php',
data: 'type=resetdate&title='+title+'&start='+start+'&end='+end+'&eventid='+event.id,
type: 'POST',
dataType: 'json',
success: function(response){
if(response.status != 'success')
revertFunc();
},
error: function(e){
revertFunc();
alert('Error processing your request: '+e.responseText);
}
});
},
eventDragStop: function (event, jsEvent, ui, view) {
if (isElemOverDiv()) {
var con = confirm('Are you sure to delete this event permanently?');
if(con == true) {
$.ajax({
url: 'process.php',
data: 'type=remove&eventid='+event.id,
type: 'POST',
dataType: 'json',
success: function(response){
console.log(response);
if(response.status == 'success'){
$('#calendar').fullCalendar('removeEvents');
getFreshEvents();
}
},
error: function(e){
alert('Error processing your request: '+e.responseText);
}
});
}
}
}
});
function getFreshEvents(){
$.ajax({
url: 'process.php',
type: 'POST', // Send post data
data: 'type=fetch',
async: false,
success: function(s){
freshevents = s;
}
});
$('#calendar').fullCalendar('addEventSource', JSON.parse(freshevents));
}
function isElemOverDiv() {
var trashEl = jQuery('#trash');
var ofs = trashEl.offset();
var x1 = ofs.left;
var x2 = ofs.left + trashEl.outerWidth(true);
var y1 = ofs.top;
var y2 = ofs.top + trashEl.outerHeight(true);
if (currentMousePos.x >= x1 && currentMousePos.x <= x2 &&
currentMousePos.y >= y1 && currentMousePos.y <= y2) {
return true;
}
return false;
}
});
process.php
<?php
define('__ROOT__', dirname(dirname(__FILE__)));
require_once __ROOT__.'/main/metodi.php';
include('config.php');
sec_session_start();
$type = $_POST['type'];
if($type == 'new')
{
$startdate = $_POST['startdate'].'+'.$_POST['zone'];
$title = $_POST['title'];
$zona_servizio = $_POST['zona_servizio'];
$insert = mysqli_query($con,"INSERT INTO calendar(`title`, `startdate`, `enddate`, `allDay`, `zona_servizio`) VALUES('$title','$startdate','$startdate','false','$zona_servizio')");
$lastid = mysqli_insert_id($con);
$_SESSION['array_last_events'][] = $lastid;
echo json_encode(array('status'=>'success','eventid'=>$lastid));
}
if($type == 'changetitle')
{
$eventid = $_POST['eventid'];
$title = $_POST['title'];
$update = mysqli_query($con,"UPDATE calendar SET title='$title' where id='$eventid'");
if($update)
echo json_encode(array('status'=>'success'));
else
echo json_encode(array('status'=>'failed'));
}
if($type == 'resetdate')
{
$title = $_POST['title'];
$startdate = $_POST['start'];
$enddate = $_POST['end'];
$eventid = $_POST['eventid'];
$update = mysqli_query($con,"UPDATE calendar SET title='$title', startdate = '$startdate', enddate = '$enddate' where id='$eventid'");
if($update)
echo json_encode(array('status'=>'success'));
else
echo json_encode(array('status'=>'failed'));
}
if($type == 'remove')
{
$eventid = $_POST['eventid'];
$delete = mysqli_query($con,"DELETE FROM calendar where id='$eventid'");
if($delete)
echo json_encode(array('status'=>'success'));
else
echo json_encode(array('status'=>'failed'));
}
if($type == 'fetch')
{
$events = array();
$query = mysqli_query($con, "SELECT calendar.id, calendar.title, calendar.startdate, calendar.enddate, zona_servizio.nome as zona_servizio, calendar.allDay FROM calendar LEFT JOIN zona_servizio on calendar.zona_servizio = zona_servizio.id");
while($fetch = mysqli_fetch_array($query,MYSQLI_ASSOC))
{
$e = array();
$e['id'] = $fetch['id'];
$e['title'] = $fetch['title'];
$e['start'] = $fetch['startdate'];
$e['end'] = $fetch['enddate'];
$e['zona_servizio'] = $fetch['zona_servizio'];
$allday = ($fetch['allDay'] == "true") ? true : false;
$e['allDay'] = $allday;
array_push($events, $e);
}
echo json_encode($events);
}
if($type == 'zone_servizio')
{
$zone = array();
$query = mysqli_query($con, "SELECT * FROM zona_servizio");
while($fetch = mysqli_fetch_array($query,MYSQLI_ASSOC))
{
$e = array();
$e['id'] = $fetch['id'];
$e['nome'] = $fetch['nome'];
$e['id_comune'] = $fetch['id_comune'];
array_push($zone, $e);
}
echo json_encode($zone);
}
?>
Explanation of the code and issue:
I'm using fullcalendar to drag and drop some events on the calendar. In the javascript this corresponds to Event receive.
After the event drop, the function saveEvent is called.
A modal is showed, with a select form.
Clicking on Save changes button, I get the selected option value and than I store the events information and this value in the DB using Ajax.
It's very linear.
When I drop the first event, everything works fine. The problem is when I drop more than one event without manually refresh the page.
Here what happen: I store the second event, but I re-store the first event too.
If I drop a third event, I re-store the first two events and the third.
I need help to understand the reason.
In the javascript I insert some console.log.
Here's the console output:
console_output
You can see at the end that the console.log "before save event" is repeated two times, with the first and second events data.
This means that at the second Event drop, the saveEvent function is called twice. So why does this happen?
I hope my question was clear. Thanks to everyone!
I resolved the issue. It was linked to the bootstrap modal.
I found this other post that helped me: link

Javascript error when trying to create a calendar

I'm brand new to javascript and php and having a slight problem.
I'm trying to create a php calendar that interacts with mysql database and have been trying to write some javascript to add events to the calendar.
My events are being brought from the mysql database but whenever I click to add an event to the calendar I get an error in the console saying "uncaught TypeError: undefined is not a function" which appears to be caused by these lines in the code:
var start = $.fullCalendar.formatDate(start, "yyyy-MM-dd HH:mm:ss");
var end = $.fullCalendar.formatDate(end, "yyyy-MM-dd HH:mm:ss");
My code is below, console log 'testing function success' is not being displayed. Please help!
$(document).ready(function() {
//get current date
var date = new Date();
var d = date.getDate();
var m = date.getMonth();
var y = date.getFullYear();
var calendar = $('#calendar').fullCalendar({
theme:true,
weekNumbers: true,
//allow a 'more' option if too many events.
eventLimit: true,
//enables agenda view
header:{
left:'prev,next today',
center: 'title',
right: 'month,agendaWeek,agendaDay'
},
events: 'event.php',
selectable: true,
selectHelper: true,
select: function(start, end, allDay) {
console.log('testing function 1');
var title = prompt('Event Title:');
if (title) {
var start = $.fullCalendar.formatDate(start, "yyyy-MM-dd HH:mm:ss");
var end = $.fullCalendar.formatDate(end, "yyyy-MM-dd HH:mm:ss");
$.ajax({
url: 'eventadd.php',
data: 'title='+ title+'&start='+ start +'&end='+ end ,
type: "POST",
success: function(json) {
console.log('testing function success');
alert('OK');
}
});
calendar.fullCalendar('renderEvent',
{
title: title,
start: start,
end: end,
allDay: allDay
},
true // make the event "stick"
);
}
calendar.fullCalendar('unselect');
},
});
});
Instead of lines
var start = $.fullCalendar.formatDate(start, "yyyy-MM-dd HH:mm:ss");
var end = $.fullCalendar.formatDate(end, "yyyy-MM-dd HH:mm:ss");
use (take care not to redefine local varialbes start, end, which are params of the function, also use Moment's format function according to: http://momentjs.com/docs/#/displaying/format/ as recommended by the fullCalendar v2 code migration):
var sfmated = start.format("yyyy-MM-dd HH:mm:ss");
var efmated = end.format("yyyy-MM-dd HH:mm:ss");
a working jsfiddle is here:
http://jsfiddle.net/xv5n1wod/12/

Categories

Resources