javascriptfullcalendarfetch-api

I'm struggling to adapt FullCalendar to push a selection event to my api endpoint so it will populate a new event


My javascript is really not strong. Ive been constructing a tool in Go and it's like 99% complete and finding FullCalendar was a godsend for displaying data. I've got it all setup and selection works great, and it's reading from my event feed just fine and populating data. But what I want is for my users to be able select the dates and get a confirmation asking if the dates are correct, and then hit the API. Heres where I am at. Pretty straight header on the html page:

  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
  <link href='https://cdn.jsdelivr.net/npm/bootstrap-icons@1.8.1/font/bootstrap-icons.css' rel='stylesheet'>

  <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
  <script src='https://cdn.jsdelivr.net/npm/fullcalendar@6.1.15/index.global.min.js'></script>

And then this is the javascript I have at the moment and it's cobbled together from various examples:

<script>

        document.addEventListener('DOMContentLoaded', function() {
            var calendarEl = document.getElementById('calendar');

            var calendar = new FullCalendar.Calendar(calendarEl, {
            selectable: true,
            selectOverlap: false,
            headerToolbar: {
                left: 'prev,next today',
                center: 'title',
                right: 'dayGridMonth'
            },
            dateClick: function(info) {
                
            },
            select: function(info) {
                // POST the data to your API endpoint.
                fetch('/api/addbooking', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(eventData)
                })
                    
                .then(response => {
                    if (!response.ok) {
                        throw new Error('Network response was not ok: ' + response.statusText);
                    }
                    return response.json();
                    })

                .then(data => {
                    console.log('Event created successfully:', data);
                    // Refresh the calendar events (assumes your events source supports refetching).
                    calendar.refetchEvents();
                })
                    
                .catch(error => {
                    console.error('Error creating event:', error);
                });
            }
        });

            calendar.render();
        });

    </script>

There is only then just the div with the id=calendar. The API at the moment is just on my machine that I am building on. I ran tcpdump and didn't see any requests coming through nor in the logging on the server end. So, my javascript is, I assume, all messed up. Is this even close? I couldn't really find a good example of this in the docs.


Solution

  • Your issue is possibly: eventData is not defined, which causes your fetch request to fail. Check your browser console, and you’ll see Uncaught ReferenceError: eventData is not defined.

    You need to define eventData inside the select function using the info object, which contains the selected date range. Try this maybe:

    select: function(info) {
        const eventData = {
            start: info.startStr,
            end: info.endStr
        };
    
        if (!confirm(`Confirm booking from ${eventData.start} to ${eventData.end}?`)) {
            return;
        }
    
        fetch('/api/addbooking', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(eventData)
        })
        .then(response => {
            if (!response.ok) {
                throw new Error('Network response was not ok: ' + response.statusText);
            }
            return response.json();
        })
        .then(data => {
            console.log('Event created successfully:', data);
            calendar.refetchEvents();
        })
        .catch(error => {
            console.error('Error creating event:', error);
        });
    }