Novica89
Novica89

Reputation: 212

jQuery full calendar $.ajax call issue ( using static events on page open )

So I am using Yii and full calendar as a widget which is called in a view of CalendarController. Uppon call for a widget, the widget retrives existing events from the DB and puts them inside the full calendar to display. Now I have also made a simple filter for filtering out events by category they are in ( dropdown with a submit ), so I want to send request to a calendarController method called actionEvents() which then takes what is passed to it ( the category of events for which we want to retrieve events ), gets them back to the jQuery which then calls the calendar again passing it a json_encode(d) array of needed properties to correctly render events under the selected category in the dropdown. The problem I have is that it seems fullcalendar is doing my wanted call ( POST ) as well as one another GET call along with it for some reason so it does return properly formatted json to the jQuery from the method of controller, but just shows an empty calendar without events in it on return. This is how the console looks like after the returned data.

enter image description here

This is the code that calls ajax call

$(document).ready(function() {
            var date = new Date(),
                d = date.getDate(),
                m = date.getMonth(),
                y = date.getFullYear();

            $('form.eventFilter').submit(function() {
                var selectedOption = $('form.eventFilter select').val(),
                    eventContainer = $('.fc-event-container');

                var objectToSend = { "categories" : [selectedOption],"datefrom" : "september2013"/*month + "" + year*/ , "dateto" : "september2013"/*month + "" + year*/};

                $.ajax({
                        url: '<?php echo Yii::app()->createUrl('calendar/events'); ?>',
                        type: "POST",
                        async:false,
                        data: {data : JSON.stringify(objectToSend)},
                        success: function(data) {

                            $('#fc_calendar').html('');
                            $('#fc_calendar').fullCalendar({
                                events: data
                            });
                            console.log(data);
                        },
                        error: function() {
                            console.log(data);
                        }

                    });

                return false;
            })
        })

The code that renders initial calendar events on first page load ( open ) is this

<div id="fc_calendar"></div>
    <script class="fc_calendar_script">
        // gets calendar and its events working and shown
        var date = new Date();
        var d = date.getDate();
        var m = date.getMonth();
        var y = date.getFullYear();

        $('#fc_calendar').fullCalendar({
            header: {
                left: 'prev,next today',
                center: 'title',
                right: 'month,basicWeek,basicDay'
            },
            editable: true,
            events: [
            <?php foreach ($eventItems as $event): ?>
            {
                title: '<?php echo htmlentities($event['eventItems']['title']); ?>',
                start: new Date(y,m,d + <?php echo $event['eventItems']['startdate_day_difference']; ?>),
                end:   new Date(y,m,d + <?php echo $event['eventItems']['enddate_day_difference']; ?>),
                url: '<?php echo $event['eventItems']['url']; ?>',
                className: [
                <?php foreach($event['eventCategories'] as $category) { echo ''.json_encode($category['slug']).','; }?> // and categories slugs as classnames, same purpose
                ]
            },
            <?php endforeach; ?>
            ]
        });
    </script>

The code in controller is not that important since you can see what it returns in the screenshot :) If someone has an idea of how to get around this I would really be grateful :) Tried everything I know

Ok so bounty goes to whoever answers this question :) I am having problems with full calendar month rendering when ajax data is returned and events populated. Since I have checkboxes for each category ( events have MANY_MANY relation with categories ) and each time a checkbox is checked or unchecked, JSON array of chosen categories of events is passed on to PHP method which queries DB for all events that go under chose categories and returns all events in a jquery encoded array to the view which then takes that events array and rerenders the calendar like shown in the upper code. Problem is that when a checkbox is checked or unchecked and ajax returned the calendar always renders on the current month ( so right now it would always rerender itself to show events for september, untill the end of the month, then always for Ocbober and so on ), but what if a user was on lets say November 2013 when he checked event category for which he wanted to filter the events? The calendar would rerender on September still. How could I make it rerender on the month the user was on when he checked / unchecked a checkbox ?

The code that I have which keeps track ( or at least it should ) of the current month when prev or next month buttons are clicked is this

$('.fc-button-next span').click(function(){
                start = $('#fc_calendar').fullCalendar('getView').visEnd;
                console.log(start);
            });

            $('.fc-button-prev span').click(function(){
                start = $('#fc_calendar').fullCalendar('getView').visStart;
                console.log(start);
            });

However this code is not tracking properly, sometimes it skips a month, sometimes it stays on the month without change and sometimes it returns propper month, which is bugging me so I cant call this function of the calendar properly which should set calendar to propper month on rerender.

$('#fc_calendar').fullCalendar('gotoDate', start);

Upvotes: 2

Views: 8428

Answers (4)

Arun P Johny
Arun P Johny

Reputation: 388396

I think what you might be looking for is something like

jQuery(function($){
    $('form.eventFilter').submit(function() {
        $('#fc_calendar').fullCalendar( 'refetchEvents' );
        return false;
    });

    $('#fc_calendar').fullCalendar({
        header: {
            left: 'prev,next today',
            center: 'title',
            right: 'month,basicWeek,basicDay'
        },
        editable: true,
        events: function(start, end, callback) {

            var selectedOption = $('form.eventFilter select').val(),
                eventContainer = $('.fc-event-container');

            //create the data to be sent
            var objectToSend = {
                "categories": [selectedOption],
                "datefrom": start.getDate() + '-' + start.getMonth() + '-' + start.getYear(),
                "dateto": end.getDate() + '-' + end.getMonth() + '-' + end.getYear()
            };          

            //use jsonp based jQuery request
            $.ajax({
                url: 'events.json',
                data: objectToSend,
                cache: false
            }).done(function(data){
                //on success call `callback` with the data
                callback(data)
            })
        }
    });
});

Demo: Plunker

Note: The date param formatting and jsonp is not used here, you will have to change it to match your requirements

Upvotes: 3

Novica89
Novica89

Reputation: 212

Actualy the problem solution is as weird as the problem itself and it is the following. You must use designated way of doing an ajax call to fetch json that is in the plugin documentation, any other way you send your own call ( GET or POST ) and the calendar after that makes yet another call ( hence the another GET call ) if you are using just a "regular" $.ajax, $.post or $.get call using jQueries native functionality This should really be posted somewhere on the website in some section so that people do not get confused why their calendar is not making ajax calls and I wonder how noone else had similar problem before . So this is the "correct" documentation way of calling it with full calendar which you can find HERE

$('#fc_calendar').html('');
                $('#fc_calendar').fullCalendar({

                    eventSources: [

                        // your event source
                        {
                            url: '?r=calendar/events',
                            type: 'POST',
                            data: { data : JSON.stringify(objectToSend)},
                            error: function(data) {
                                alert(data);
                            },
                        }

                        // any other sources...

                    ]

                });

So it will automaticly fetch any returned ( properly formatted data ) and use it to rerender new calendar with those events. It is very weird way of doing it, but the only way that will work.

Upvotes: 1

Ionut Flavius Pogacian
Ionut Flavius Pogacian

Reputation: 4811

I see that you use JSON.stringify(data); this is what i tought your error was

maybe you need a jsonp, and below you have my example

$.ajax({
            'url': 'http://domain.com/index.php/api/news?callback=?',
            'data': {'data': JSON.stringify(data), callback: 'jsonPCallback'},
            'success': function(data) {
//                console.log(data);
            },
            jsonpCallback: jsonPCallback,
            dataType: 'jsonp'
        });

function jsonPCallback(cbdata){
        console.log('callback2')
//        console.log(cbdata);
        return false;
    }

now, do you also use something like

echo $_GET['callback'].'('.CJSON::encode(array('status_live' => 1, 'data' => $data_decoded)).')';

in the controller to return the results ?

also, createUrl might be wrong, because you need a absolute path

Upvotes: 1

Developerium
Developerium

Reputation: 7265

I can't comment so, you have an assignment to variable:"nothing" in your last query parameter

double check if you have looked for ajax request in your controller(important!),

and also if this is this a 404 by the apache, you have url rewriting problems, and it looks like index.php is missing from url?!

Upvotes: 0

Related Questions