What is the best way to manage a JSON feed that does not provide any results?

Excuse my lack of experience as I pose my first question. Using FullCalendar 5.10.1, I am working on retrieving events dynamically associated with Festivals.

I have followed the 'events (as a json feed)' pattern from the documentation. When there is at least one event linked to the selected Festival, everything works smoothly and the calendar displays the event(s) correctly.

However, if the feed does not locate any events associated with the Festival selection, the failure callback triggers immediately. An error message 'Failure parsing JSON' appears in the Console. Dismissing the failure message loads an empty calendar as expected.

It's evident that I haven't properly handled the scenario where no events are found, but I'm unsure whether this should be addressed in the feed SQL or within the FullCalendar code.

This setup is running inside a Bootstrap tab. Some temporary code is included here to address a conflict issue with a vendor's theme by delaying the calendar load after setting a variable to the id of the calendar tab.

Admittedly, I may not have presented the code optimally here and possibly did not explain the issue thoroughly enough. Any guidance for this beginner would be greatly appreciated.

<script type="text/javascript">

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

      themeSystem: 'bootstrap',
      headerToolbar: {
        left: 'prev,next today',
        center: 'title',
        right: 'dayGridMonth,timeGridWeek,timeGridDay'
      },
      weekNumberCalculation: "ISO",
      initialView: 'dayGridMonth',
      initialDate: '2021-07-01',
      eventDidMount: function(info) {
        $(info.el).tooltip({
          title: info.event.extendedProps.description,
          placement: 'top',
          trigger: 'hover',
          container: 'body'
        });
      },
      eventSources: [
        {
          url: '/DesktopModules/XModPro/Feed.aspx',
          method: 'POST',
          datatype: 'JSON',
          extraParams: {
            pid: '0',
            xfd: 'Events_FullCalendar_FestivalID',
            FestivalID: '[[FestivalID]]'
          },
          failure: function() {
            alert('There was an error while fetching events!');
          },

          color: '#a1a535',   // a non-ajax option
          textColor: 'white' // a non-ajax option
        }
      ]
    });

    calendarButton.addEventListener('click', e => {
      setTimeout(() => {calendar.render()}, 1);
    });
  });
</script>

Feed SQL

<%@ Control Language="vb" AutoEventWireup="false" Inherits="KnowBetter.XModPro.FeedBase" %>
<%@ Register Assembly="KnowBetter.XModPro.Web.Controls" Namespace="KnowBetter.XModPro.Web.Controls" TagPrefix="xmod" %>
<xmod:masterview runat="server">
<xmod:JsonFeed runat="server">              
 
<ListDataSource CommandText="SELECT
                             EventID AS 'id',
                             VenueID AS 'vid',
                             FestivalID,
                             EventTitle AS 'title',
                             EventDescription AS 'description',
                             EventStartTime AS 'start',
                             EventEndTime AS 'end'

                            FROM la360_Event
                            WHERE FestivalID = @FestivalID">

<Parameter Name = "FestivalID" value= '<%#FormData("FestivalID")%>' DataType="string" />
</ListDataSource>

</xmod:JsonFeed></xmod:masterview>

Answer №1

I wanted to share my 'solution' here for anyone who may benefit from it in the future. By using UNION, I was able to insert a null event record into the feed result. This ensures that FullCalendar continues to function even when there are no actual events. While my syntax may not be the most elegant or well-written, both FullCalendar and I are pleased with the outcome.

<ListDataSource CommandText="SELECT
                         null AS 'id',
                         null AS 'vid',
                         null AS 'FestivalID',
                         null AS 'title',
                         null AS 'description',
                         null AS 'start',
                         null AS 'end'
                         
                         UNION
                                               
                         SELECT
                         EventID AS 'id',
                         VenueID AS 'vid',
                         FestivalID,
                         EventTitle AS 'title',
                         EventDescription AS 'description',
                         EventStartTime AS 'start',
                         EventEndTime AS 'end'

                         FROM la360_Event
                         WHERE FestivalID = @FestivalID">

                        <Parameter Name = "FestivalID" value= '[[Form:FestivalID]]' DataType="int32"/>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

When the search button is clicked to find a specific address, the React Google Maps API fails to zoom in on

How can we modify this code to achieve the functionality where, upon clicking the search button, the map zooms in closer to the address entered by the user, similar to how it works on Google Maps? The goal is to replicate the search feature from the Goog ...

Examining the contents of an array in JavaScript

I am currently conducting API testing. My objective is to verify the presence of a specific name within the API response. The data from the API response is structured in an array format. Despite my intention to check for the existence of the name "activ ...

Comparing Dates in Node.js using JavaScript and Sorting Arrays based on Date Values

Is JavaScript lacking a basic Date comparison feature similar to Python? Within my Node.js script, these lines are present: console.log(Date(2012,11,10) < Date(2012, 11, 9)) console.log(Date(2012,11,10) > Date(2012, 11, 9)) Surprisingly, both of t ...

Implementing a rail ajax remote form to automatically update a text field after submission

My main goal is to dynamically update a text field on my webpage with a specific value after submitting a remote form using Rails. If you are interested, you can find all the source code on github at this link: https://github.com/iamliamnorton/fasdac The ...

The JavaScript promise remains in limbo, neither resolving nor rejecting, seemingly stuck for unknown reasons

In the process of developing a node script, I encountered an issue where the images were not being ordered according to the calculated score value. The score is determined by a function named getImageScore(), which unfortunately takes a considerable amount ...

Parsing improperly formatted JSON from an HTTP GET request can be done using either AngularJS or JQuery

Trying to decipher a poorly formatted JSON response from a remote server that looks something like this: //[ {},{} ] In my AngularJS code: $http.get('http://www.example.com/badjson') .success(function(data) { console.log(data); }) ...

Issue with custom Javascript not executing in Internet Explorer versions 9 and 10

Initially, this script is found in the document's head section. <script> document.addEventListener("DOMContentLoaded", function () { var e, t = document.querySelectorAll("div.bounceInDown"); for (var n = 0, r = t.length; n & ...

Passing arguments with $emit - Vue

Here is a simple method to handle alerts using $emit. But when passing arguments, it seems like the event is not being triggered at all. The goal is to update the value of alert with the result. Listening for the event on mount: this.$eventHub.$on(' ...

Submitting data to an external PHP file using the JavaScript function $.post

Having issues with the PHP page function ajaxFunction(){ var ajaxRequest; try{ ajaxRequest = new XMLHttpRequest(); } catch (e){ try{ ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try{ ajaxRequ ...

Create basic HTML using the react.cloneElement method

When using React.cloneElement(), the first parameter always needs to be a react component that is passed as children in props. Is there a way to pass a simple HTML node as a child? Please see the example code below for clarification: Dialog.jsx (Common c ...

The $routeProvider is unable to load the view specified in ngRoute

I am currently in the process of implementing ngRoute into my application, but I am facing challenges with getting it to function properly. To showcase my efforts, I have developed a basic app. index.html: <!DOCTYPE html> <html ng-app="tester"& ...

Acquiring the selector value from a tag

To summarize: This snippet of code: for(let i = 0; i <= items.length; i++){ console.log(items[i]) } Produces the following output: <a class="photo ajax2" target="_blank" href="/profile/show/3209135.html" data-first="1" data-next="3206884"> ...

Top method for organizing Vue JS elements

I am looking to integrate a search feature on my website using Vue 2, where the search functionality will be applied to components generated from a JSON file upon page load. The JSON file contains the keywords I want to utilize for the search - specifical ...

Tips for securing a navbar in material ui

https://i.stack.imgur.com/CYfmQ.png In my current React project, I am facing an issue with aligning components within the Material-UI AppBar Component. My aim is to achieve a seamless and perfectly straight alignment for three key elements: a logo image, ...

Once the PHP page loads, it becomes challenging for me to dynamically change values in JavaScript

Within my code snippet below, I am aiming to modify the initial value using a slider. The slider appears to be functioning correctly; however, it is not updating the values of timeout as indicated beneath the line $('ul.<?php echo $this->session ...

Step-by-Step Guide for Attaching Table Legs

I believe that the four legs should be an integral part of the table, rather than just added on like an afterthought. What would be the best way to create new instances of legs and attach them in a way that makes the back legs look slightly smaller than t ...

The initial ajax request successfully connects to the file, but encounters a 404 error upon the second attempt

I am currently encountering an issue with a jQuery post function. The function is designed to run multiple times and then stop, which it has successfully done in the past. However, now the problem arises when the function tries to execute itself again afte ...

Performing an HTTP GET request in NodeJS to a specific URL in order to receive

Currently, I am attempting to execute a server-side API call using a RESTful protocol that delivers a JSON response. To better understand this process, I have extensively studied the API documentation as well as explored information provided in this partic ...

Is webpack necessary for segregating dependencies during installation?

Currently, I'm diving into a tutorial on webpack and it's been three days already, but confusion still reigns! I am delving into the commands: npm i webpack --save-dev I find myself puzzled by the '--save-dev' in the above command whi ...