0

I am trying to make a schedule of school classes, I have integrated "drag and drop" and the events are saved in the database but these are shown only during the week to which the date indicated to the event belongs. I would like that even if the current date changes to the following week, the events would still be visible and would depend on the day of the week and not on the full date.

To get the events I use the following line:

        events: "../ajax/fullcalendar/response.php?view=1",

But in this question I saw an issue similar to what I want to do, but there they use a POST request as below

    $.post( "getevents2.php",
            {'getEvents': 1},
            function(data) {
                var array = JSON.parse(data);
                for(i = 0; i < array.length; i++) {
                    $('#calendar').fullCalendar( 'renderEvent', {
                        title: 'Sometitle',
                        start: days[array[i]['day']]+'T'+array[i]['start_time'], // here we are setting needed date from array 'days' by day's name which we got from database
                        end: days[array[i]['day']]+'T'+array[i]['end_time']     // here's the same
                    } );
                }
            }
    );

I got confused when trying to combine both codes, because the console tells me an error: "Unexpected end of JSON entry in JSON.parse (), I also saw that the person also added an array of Days to not use the full date, so When I combine my code with the other mentioned question, my code has been as follows:

        //Custom
        //De momento esta funcion no se usa, asi que, sigue usando fecha completa en lugar de solo 7 dias, asi que en teoria, los eventos desapareceran cuando avance el tiempo 
         Date.prototype.getDaysOfCurrentWeek = function(start)
            {
                // Array of all days of week
                var days = [ "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];

            // Calculates date of first day of current week
            start = start || 0;
            var today = new Date(this.setHours(0, 0, 0, 0));
            var day = today.getDay() - start;
            var date = today.getDate() - day;

            // Then we are calculating all dates of current week and then reformat them into ISOO
            var daysOfWeek = new Object();
            for(i = 0; i < 8; i++) {
                tmp = new Date(today.setDate(date+i));
                daysOfWeek[days[i]] = tmp.getFullYear()+'-'+(tmp.getMonth()+1)+'-'+tmp.getDate();
            }

            return daysOfWeek;
        }
        //Ends Custom

        var days = new Date().getDaysOfCurrentWeek(); // gets array like ('nameOfDay' => 0000-00-00)
        $(document).ready(function(){


            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 .external-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
                        color: $.trim($(this).data("color")),
                        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
                    });

                });     
                ////////////////

                var calendar = $('#calendar').fullCalendar({
                    header:{
                        left: 'prev,next today',
                        center: 'title',
                        right: 'month,agendaWeek,agendaDay'
                    },

                    defaultView: 'agendaWeek',  //agendaWeek
                    editable: true,
                    selectable: true,
                    allDaySlot: false,
                    //Custom
                             // allDaySlot: false,  //repetido
                              hiddenDays: [0],  //Ocultar Domingo
                              columnFormat: 'dddd',
                              minTime: '07:00:00',
                              maxTime: '22:00:00',
                              slotDuration: "00:50:00", //Cada 54 minutos
                              slotLabelInterval: 50,
                              //slotMinutes: 54,
                              slotLabelFormat: 'h(:mm)a',
                              header: true,     //lo cambie a false para esconderlo y cuando lo devolvi a true ya no aparecio el encabezado



                                                droppable: true, 
                    //Ends Custom


                    events: "../ajax/fullcalendar/response.php?view=1", //De  las lineas 87 a 101, no funciono, descomentar 102



                    eventClick:  function(event, jsEvent, view) {
                        endtime = $.fullCalendar.moment(event.end).format('h:mm');
                        starttime = $.fullCalendar.moment(event.start).format('dddd, MMMM Do YYYY, h:mm');
                        var mywhen = starttime + ' - ' + endtime;
                        $('#modalTitle').html(event.title);
                        $('#modalWhen').text(mywhen);
                        $('#eventID').val(event.id);
                        $('#calendarModal').modal();
                    },

                    //header and other values
                    select: function(start, end, jsEvent) {
                        endtime = $.fullCalendar.moment(end).format('h:mm');
                        starttime = $.fullCalendar.moment(start).format('dddd, MMMM Do YYYY, h:mm');
                        var mywhen = starttime + ' - ' + endtime;
                        start = moment(start).format();
                        end = moment(end).format();
                        $('#createEventModal #startTime').val(start);
                        $('#createEventModal #endTime').val(end);
                        $('#createEventModal #when').text(mywhen);
                        $('#createEventModal').modal('toggle');
                   },




                                                //custom
                                                eventReceive: function(event){
                                                    var title = event.title;
                                                    var color = event.color;
                                                    $.ajax({
                                                        url: '../ajax/fullcalendar/response.php',
                                                        data: 'action=add&title='+title+'&start='+moment(event.start).format()+'&end='+moment(event.end).format()+'&color='+color,
                                                        type: 'POST',
                                                        dataType: 'json',
                                                        success: function(response){                        
                                                            event.id = response.eventid;
                                                            $('#calendar').fullCalendar('updateEvent',event);

                                                        },
                                                        error: function(e){
                                                            console.log(e.responseText);

                                                        }
                                                    });
                                                    $('#calendar').fullCalendar('updateEvent',event);


                                                    console.log(event);

                                                },
                                                //custom


                   eventDrop: function(event, delta){
                       $.ajax({
                           url: '../ajax/fullcalendar/response.php',
                           data: 'action=update&title='+event.title+'&start='+moment(event.start).format()+'&end='+moment(event.end).format()+'&id='+event.id ,
                           type: "POST",
                           success: function(json) {
                           //alert(json);
                           }
                       });
                   },
                   eventResize: function(event) {
                       $.ajax({
                           url: '../ajax/fullcalendar/response.php',
                           data: 'action=update&title='+event.title+'&start='+moment(event.start).format()+'&end='+moment(event.end).format()+'&id='+event.id,
                           type: "POST",
                           success: function(json) {
                               //alert(json);
                           }
                       });
                   },

                                            //custom
                                            eventDragStop: function (event, jsEvent, ui, view) {
                                                if (isElemOverDiv()) {
                                                        var eventID = $('#eventID').val();
                                                    var con = confirm('&iquest;Estas seguro de eliminar este evento permanentemente?');
                                                    if(con == true) {
                                                        $.ajax({
                                                            url: '../ajax/fullcalendar/response.php',
                                                            data: 'action=delete&id='+event.id,
                                                            type: 'POST',
                                                            dataType: 'json',
                                                            success: function(response){
                                                                console.log(response);
                                                    //          if(response.status == 'success'){
                                                                    //$('#calendar').fullCalendar('removeEvents');
                                                                    //$("#calendar").fullCalendar('removeEvents',+eventID);
                                                    //              $("#calendar").fullCalendar('removeEvents',+response.idEvent);
                                                                    //getFreshEvents();

                           if(response == 1)
                                //$("#calendar").fullCalendar('removeEvents',eventID);
                                $("#calendar").fullCalendar('removeEvents',event.id);
                           else
                                return false;


                            $('#calendar').fullCalendar( 'refetchEvents' );
                                                    //          }
                                                            },
                                                            error: function(e){ 
                                                                alert('Error processing your request: '+e.responseText);
                                                            }
                                                        });
                                                    }   
                                                }
                                            }
                                            //custom

                });



               $('#submitButton').on('click', function(e){
                   // We don't want this to act as a link so cancel the link action
                   e.preventDefault();
                   doSubmit();
               });

               $('#deleteButton').on('click', function(e){
                   // We don't want this to act as a link so cancel the link action
                   e.preventDefault();
                   doDelete();
               });

               function doDelete(){
                   $("#calendarModal").modal('hide');
                   var eventID = $('#eventID').val();
                   $.ajax({
                       url: '../ajax/fullcalendar/response.php',
                       data: 'action=delete&id='+eventID,
                       type: "POST",
                       success: function(json) {
                           if(json == 1)
                                $("#calendar").fullCalendar('removeEvents',eventID);
                           else
                                return false;


                       }
                   });
               }
               function doSubmit(){
                   $("#createEventModal").modal('hide');
                   var title = $('#title').val();
                   var startTime = $('#startTime').val();
                   var endTime = $('#endTime').val();
                   var color = $('#color').val();

                   $.ajax({
                       url: '../ajax/fullcalendar/response.php',
        //               data: 'action=add&title='+title+'&start_time='+startTime+'&end_time='+endTime,     //start='+startTime+'&end='+endTime,        //Si no regreso a como estaba devuelve 1970
                       data: 'action=add&title='+title+'&start='+startTime+'&end='+endTime+'&color='+color,     //Si no regreso a como estaba devuelve 1970
                       type: "POST",
                       success: function(json) {


                           $("#calendar").fullCalendar('renderEvent',
                           {
                               id: json.id,
                               title: title,
                               start: startTime,
                               end: endTime,
                               color: color,
                                //start: days[array[i]['day']]+'T'+array[i]['start_time'], // here we are setting needed date from array 'days' by day's name which we got from database
                                //end: days[array[i]['day']]+'T'+array[i]['end_time']     // here's the same
                           },

                           true);

                           //alert(json);

                       }
                   });


               }




            function getFreshEvents(){
                $.ajax({
                    url: '../ajax/fullcalendar/response.php',
                    type: 'POST', // Send post data
                    data: 'view=1',
                    async: false,
                    success: function(s){
                        freshevents = s;
                    }
                });
                $('#calendar').fullCalendar('addEventSource', s.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;
            }

            });
SecretAgentMan
  • 2,856
  • 7
  • 21
  • 41
Manuel Ruiz
  • 29
  • 1
  • 9
  • If you just want your events to repeat weekly at the same day and time, see the first section of this answer: https://stackoverflow.com/a/29393128/5947043 – ADyson Feb 20 '19 at 08:43
  • 1
    P.S. I think most of the code above is almost certainly irrelevant to your specific question, but to my eyes it seems like you have made your page extremely complicated. I would be willing you bet you could simplify that code quite a lot with a bit of thought. Particularly anywhere that you do manual manipulation of date strings - far easier to use momentJS functions instead to do calculations and convert between formats. Also the fact that the spacing and indentation is dreadful doesn't help with the overall impression, but I'm guessing that maybe happened when you pasted it into here. – ADyson Feb 20 '19 at 12:31

0 Answers0