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!
Related
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");
...
}
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
I have a button that can be clicked that will bring up a popup box with one textfield. Whenever, I enter something and click "Add", I want it to be inserted into my database.
Currently, when I click "Add", it will insert into the DB, but it will not read the value entered. Therefore, a null value is simply entered. I get no errors that I can see, however in my JavaScript I do a console.log(dict) and the output in the log is Object {} so it doesn't look like the entered value is being logged. I also am getting a successful row inserted message in the logs too so I would definitely think that it is just a matter of being able to get the values to be read.
So my question is how can I get it to read the value and successfully enter it into the database.
HTML of Add button:
<td><button class="create-user" id="insertButton">Add Group</button></td>
HTML of Popup Box:
<div id="dialog-form" title="Add Group">
<p class="validateTips">Please Add a Group</p>
<!-- Dialog box displayed after add row button is clicked -->
<form>
<fieldset>
<label for="sku_group">SKU Group</label>
<input type="text" name="group" id="group" class="text ui-widget-content ui-corner-all">
<!-- Allow form submission with keyboard without duplicating the dialog button -->
<input type="submit" id="submit" tabindex="-1" style="position:absolute; top:-1000px">
</fieldset>
</form>
</div>
JavaScript:
// ----- Dialog Box for adding a row -----
$( function() {
var dialog, form,
sku_group = $( "#group" ),
allFields = $( [] ).add( sku_group ),
tips = $( ".validateTips" );
console.log(allFields);
function updateTips( t ) {
tips
.text( t )
.addClass( "ui-state-highlight" );
setTimeout(function() {
tips.removeClass( "ui-state-highlight", 1500 );
}, 500 );
}
function checkRegexp( o, regexp, n ) {
if ( !( regexp.test( o.val() ) ) ) {
o.addClass( "ui-state-error" );
updateTips( n );
return false;
} else {
return true;
}
}
function addGroup() {
var valid = true;
allFields.removeClass( "ui-state-error" );
// ----- Validation for each input in add row dialog box -----
valid = valid && checkRegexp( sku_group, /^[a-z]([0-9a-z_\s])+$/i, "Please enter a valid SKU Group name" );
console.log(allFields);
if ( valid ) {
var $tr = $( "#skuTable tbody tr" ).eq(0).clone();
var dict = {};
var errors = "";
$.each(function(){
$tr.find('.' + $(this).attr('id')).html( $(this).val()+"-"+sku_group );
var type = $(this).attr('id');
var value = $(this).val();
console.log(type + " : " + value);
// ----- Switch statement that provides validation for each table cell -----
switch (type) {
case "group":
dict["SKU Group"] = value;
break;
}
});
$( "#skuTable tbody" ).append($tr);
dialog.dialog( "close" );
console.log(dict);
var request = $.ajax({
type: "POST",
url: "insert-group.php",
data: dict
});
request.done(function (response, textStatus, jqXHR){
if(JSON.parse(response) == true){
console.log("row inserted");
} else {
console.log("row failed to insert");
console.log(response);
}
});
// Callback handler that will be called on failure
request.fail(function (jqXHR, textStatus, errorThrown){
console.error(
"The following error occurred: "+
textStatus, errorThrown
);
});
// Callback handler that will be called regardless
// if the request failed or succeeded
request.always(function () {
});
}
return valid;
}
var dialog = $( "#dialog-form" ).dialog({
autoOpen: false,
height: 400,
width: 350,
modal: true,
buttons: {
"Add Group": addGroup,
Cancel: function() {
dialog.dialog( "close" );
}
},
close: function() {
form[ 0 ].reset();
}
});
form = dialog.find( "form" ).on( "submit", function( event ) {
event.preventDefault();
addGroup();
});
$( ".create-user" ).button().on( "click", function() {
dialog.dialog({
show: 'blind',
hide: 'blind'
});
dialog.dialog("open");
});
});
insert-group.php script:
<?php
$SKU_Group = $_POST['SKU Group'];
$host="xxxxxxxxxxx";
$dbName="xxxxxxx";
$dbUser="xxxx";
$dbPass="xxxxxxxxxxxxxx";
$pdo = new PDO("sqlsrv:server=".$host.";Database=".$dbName, $dbUser, $dbPass);
$sql = "INSERT INTO SKU_Group_Dim ([SKU Group]) VALUES (?)";
$stmt = $pdo->prepare($sql);
$result = $stmt->execute(array($SKU_Group));
echo json_encode($result);
?>
EDIT
My html table:
<table id="skuTable" cellspacing="5" class="ui-widget ui-widget-content">
<thead>
<tr class="ui-widget-header">
<th class="skuRow">SKU Group</th>
<th class="skuRow">Group ID</th>
<th class="skuRow">Edit</th>
<th class="skuRow">Delete</th>
</tr>
</thead>
<tbody>
<?php foreach ($dbh->query($sql_table) as $rows) { ?>
<tr>
<td class="sku_group" id="sku_group-<?php echo intval ($rows['SKU Group'])?>"><?php echo $rows['SKU Group']?></td>
<td class="group_id" align="center" id="group_id-<?php echo intval ($rows['Group_ID'])?>"><?php echo $rows['Group_ID']?></td>
<td><button type="button" class="edit" name="edit">Edit</button></td>
<td><button type="button" class="delete" onclick="deleteRow(this)">Delete</button></td>
</tr>
<?php
}
?>
</tbody>
</table>
Your value does not good
Try to change
var value = $(this).val();
To
var value = $(this).find('input[type=text]').val();
Try changing your $.each function to $tr.each. I think you should provide something for it to iterate over. Here is the link to .each() documentation..
If you want to iterate over all 's you have to add td to jquery call.
My fix would look like this:
var $tr = $( "#skuTable tbody tr td" ).eq(0).clone(); //get all td of sku-table
var dict = {};
$tr.each(function(){
var type = $(this).attr('id'); // get value of current tr
var value = $(this).html(); // get html content inside of tr
switch (type) {
case "group":
dict["SKU Group"] = value;
break;
}
});
$('#group').val(dict['SKU Group']); // set value of the input field
I have a button that can be clicked that will bring up a popup box with one textfield. Whenever, I enter something and click "Add", I want it to be inserted into my database.
Currently, when I click "Add", it will insert into the DB, but it will not read the value that was entered. Therefore, a null value is simply entered. I get no errors that I can see, however in my JavaScript I do a console.log(type + " : " + value); and it returns sku_group-0 : in the logs. I also do a console.log(dict) and the output in the log is Object {} so it doesn't look like the entered value is being logged. I also am getting a successful row inserted message in the logs too so it definitely looks like it is just a matter of being able to get the values to be read so they can then be processed in the insert-group.php script.
So my question is how can I get it to read the value in the JavaScript so that it can be successfully entered into the database?
HTML of Popup Box:
<div id="dialog-form" title="Add Group">
<p class="validateTips">Please Add a Group</p>
<!-- Dialog box displayed after add row button is clicked -->
<form>
<fieldset>
<label for="sku_group">SKU Group</label>
<input type="text" name="group" id="group" class="text ui-widget-content ui-corner-all">
<!-- Allow form submission with keyboard without duplicating the dialog button -->
<input type="submit" id="submit" tabindex="-1" style="position:absolute; top:-1000px">
</fieldset>
</form>
</div>
HTML of Add button:
<button class="create-user" id="insertButton">Add Group</button>
JavaScript:
$( function() {
var dialog, form,
sku_group = $( "#group" ),
allFields = $( [] ).add( sku_group ),
tips = $( ".validateTips" );
console.log(allFields);
function updateTips( t ) {
tips
.text( t )
.addClass( "ui-state-highlight" );
setTimeout(function() {
tips.removeClass( "ui-state-highlight", 1500 );
}, 500 );
}
function checkRegexp( o, regexp, n ) {
if ( !( regexp.test( o.val() ) ) ) {
o.addClass( "ui-state-error" );
updateTips( n );
return false;
} else {
return true;
}
}
function addGroup() {
var valid = true;
allFields.removeClass( "ui-state-error" );
// ----- Validation for each input in add row dialog box -----
valid = valid && checkRegexp( sku_group, /^[a-z]([0-9a-z_\s])+$/i, "Please enter a valid SKU Group name" );
console.log(allFields);
if ( valid ) {
var $tr = $( "#skuTable tbody tr td" ).eq(0).clone();
var dict = {};
var errors = "";
$tr.each(function(){
var type = $(this).attr('id');
var value = $(this).html();
console.log(type + " : " + value);
switch (type) {
case "group":
dict["SKU Group"] = value;
break;
}
});
$( "#skuTable tbody" ).append($tr);
dialog.dialog( "close" );
console.log(dict);
var request = $.ajax({
type: "POST",
url: "insert-group.php",
data: dict
});
request.done(function (response, textStatus, jqXHR){
if(JSON.parse(response) == true){
console.log("row inserted");
} else {
console.log("row failed to insert");
console.log(response);
}
});
// Callback handler that will be called on failure
request.fail(function (jqXHR, textStatus, errorThrown){
console.error(
"The following error occurred: "+
textStatus, errorThrown
);
});
// Callback handler that will be called regardless
// if the request failed or succeeded
request.always(function () {
});
}
return valid;
}
var dialog = $( "#dialog-form" ).dialog({
autoOpen: false,
height: 400,
width: 350,
modal: true,
buttons: {
"Add Group": addGroup,
Cancel: function() {
dialog.dialog( "close" );
}
},
close: function() {
form[ 0 ].reset();
}
});
form = dialog.find( "form" ).on( "submit", function( event ) {
event.preventDefault();
addGroup();
});
$( ".create-user" ).button().on( "click", function() {
dialog.dialog({
show: 'blind',
hide: 'blind'
});
dialog.dialog("open");
});
});
insert-group.php script:
<?php
$SKU_Group = $_POST['SKU Group'];
$host="xxxxxxxxxxx";
$dbName="xxxxxxx";
$dbUser="xxxx";
$dbPass="xxxxxxxxxxxxxx";
$pdo = new PDO("sqlsrv:server=".$host.";Database=".$dbName, $dbUser, $dbPass);
$sql = "INSERT INTO SKU_Group_Dim ([SKU Group]) VALUES (?)";
$stmt = $pdo->prepare($sql);
$result = $stmt->execute(array($SKU_Group));
echo json_encode($result);
?>
REPLACE
"data: dict"
WITH
data:{ 'SKU_Group' : $('#group').val() }
AND
REPLACE
"$SKU_Group = $_POST['SKU Group'];"
WITH
$SKU_Group = $_POST['SKU_Group'];
You should get your input value with:
$('#group').val()
My code is as below.
<script>
var t=<?php echo json_encode($ta)?>;
var d=<?php echo json_encode($da)?>;
$(document).ready(function() {
$('#calendar').fullCalendar({
//defaultDate: '2016-03-12',
editable: true,
eventLimit: true, // allow "more" link when too many events
//$r=$ev->title;
for(var j=0;j<d.length;j++)
{
events: [{
title: t[j],
start: d[j]
}
]
}
});
});
</script>
I have used the fullcalendar 2.6.1. But nothing displayed. Please can anybody help me? I want to retrieve all the title and eventDate from the db and view in the calendar. The var t and d contains the all the data of $ta and $da arrays. I just wanted to assign them to events array title and start keywords.There are some red marks indicate that for loop is going to be wrong.
Try this one
<?php
$ta=array();
$i=0;
?>
#foreach($events as $ev)
<?php
$ta[$i]['title'] = $ev->title;
$ta[$i]['start'] = date('Y-m-d H:i:s', strtotime($ev->eventDate));
$i++;
?>
#endforeach
<script>
var t=<?php echo json_encode($ta)?>;
$(document).ready(function() {
$('#calendar').fullCalendar({
//defaultDate: '2016-03-12',
editable: true,
eventLimit: true, // allow "more" link when too many events
events: t,
eventRender: function(event, element) {
$('.fc-time', element).hide();
}
});
});
</script>
$.ajax({
url:'',
dataType: 'json',
success: function(doc) {
var events = [];
$.each(doc, function(key, value){
events.push({
title : value['title name'],
start : value['hours'],
backgroundColor: Metronic.getBrandColor('yellow'),
id : value['id']
});
});
AddFullCalenderEvent(events);
}
});
function AddFullCalenderEvent(eventList){
$('#calendar').fullCalendar({
events: eventList,
eventClick: function(event) {
// opens events in a popup window
window.location.href = "pagename?id=" + event.id;
return false;
}
Try this