Events are not appearing on the fullcalendar display

I am trying to integrate events into the fullcalendar plugin. A web method in my ASPX file generates JSON data for the JavaScript code. However, I am facing difficulty in connecting the result of the web method with the full calendar. Currently, I can only manually add events.

Below is the JavaScript code:

$(document).ready(function () {
    $('#btnInit').click(function () {
        var start = Date.parse($("#MainContent_dateD").text());
        var end = Date.parse($("#MainContent_dateF").text());
        var cle = $("#MainContent_HF_cleU").val();
        $.ajax({
            type: "POST",
            url: "ConsultationPlanning.aspx/getPlanning",
            data: '{"start": "' + start + '", "end": "' + end + '"}',
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (msg) {
                if (msg == null) {
                    alert('no result');
                    return;
                }
                alert("received: " + msg.d);
                document.getElementById("MainContent_dateD").innerHTML = msg.d;
                $('#calendar').fullCalendar({
                    eventSources: JSON.parse(msg.d)
                });
            },
            error: function(msg){
                alert("error: " + msg);
            }
        });
    });

    // FullCalendar initialization
    $('#calendar').fullCalendar({
        header: {
            left: 'prev,next today',
            center: 'title',
            right: 'month,agendaWeek,agendaDay'
        },
        hiddenDays: [0],
        defaultView: 'month',
        editable: false,
        allDaySlot: false,
        selectable: false,
        eventSources: [{
            url: 'ConsultationPlanning.aspx/getPlanning'
        }]
    });
})

In the initial setup, the parameters in the web methods were strings. Here is the code from the ASPX.CS file:

public static String getPlanning(string start, string end)
{
    List<String> ls1 = new List<string>();
    IList<Planning> ls2= new List<Planning>();

    DateTime t = Convert.ToDateTime(start);
    DateTime t2 = t.AddHours(1.0);
    Planning p=new Planning();

    for (int i = 0; i < 4; i++)
    {
        p.id = "" + i + "" ;
        p.title = "event "+i ;
        p.start = String.Format("{0:s}", t.AddDays(Convert.ToDouble(i)));
        p.end = String.Format("{0:s}", t2.AddDays(Convert.ToDouble(i)));
        ls2.Add(p);
    }
    System.Web.Script.Serialization.JavaScriptSerializer oSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
    string sJSON = oSerializer.Serialize(ls2);
    return sJSON;
}

I have validated the JSON data using jsonlint.com, so I believe the issue lies within the JavaScript code, but I cannot locate it.

Here is an example of the JSON data:

[
    {"id":"0","title":"event 0","start":"2015-05-04T12:35:37","end":"2015-05-04T13:35:37"},
    {"id":"1","title":"event 1","start":"2015-05-05T12:35:37","end":"2015-05-05T13:35:37"},
    {"id":"2","title":"event 2","start":"2015-05-06T12:35:37","end":"2015-05-06T13:35:37"},
    {"id":"3","title":"event 3","start":"2015-05-07T12:35:37","end":"2015-05-07T13:35:37"}
]

Answer №1

Include the code events: [<%=getPlanning%>] while deleting the line with eventSources.

Answer №2

If you want to filter events within a specific range, consider implementing this code snippet and let the callback function work its magic:

eventSources: {
    events: function (start, end, callback) {
        $.ajax({
           type: "POST",
           url: "ConsultationPlanning.aspx/getPlanning",
           data: '{ "start": "' + start.toISOString() + '", "end": "' + end.toISOString() + '" }',
           contentType: "application/json; charset=utf-8",
           dataType: "json",
           success: function (msg) {
               callback(msg.d);
           } 
        }
    }
}

To ensure it functions correctly, make sure to update your server method signature with DateTime parameters...

Answer №3

The calendar was not loading data correctly because it was initially loaded in the full calendar without events. It seems like adding an event source could solve the issue. Moving the call within the document.ready(function) helped to retrieve the JSON result as an event instead of an eventSource:

$(document).ready(function () {
var start = Date.parse($("#MainContent_dateD").text());
var end = Date.parse($("#MainContent_dateF").text());
var cle = $("#MainContent_HF_cleU").val();

$.ajax({
    type: "POST",
    url: "ConsultationPlanning.aspx/getPlanning",
    data: '{"start": "' + start + '", "end": "' + end + '"}',
    contentType: "application/json; charset=utf-8",
    dataType: "json",

    success: function (msg) {
        if (msg == null) {
            alert('no result');
            return;
        }

        $('#calendar').fullCalendar({
            header: {
                left: 'prev,next today',
                center: 'title',
                right: 'month,agendaWeek,agendaDay'
            },
            hiddenDays: [0],
            defaultView: 'month',
            editable: false,
            allDaySlot: false,
            selectable: false,
            events: JSON.parse(msg.d)
        });
    },

    error: function(msg){
        alert("function not working : " + msg);
    }
});
})

I am open to suggestions on how to enhance the code further.

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

What is the best way to incorporate background colors into menu items?

<div class="container"> <div class="row"> <div class="col-lg-3 col-md-3 col-sm-12 fl logo"> <a href="#"><img src="images/main-logo.png" alt="logo" /> </a> ...

Having trouble adding items to an array within a Javascript promise

I am facing an issue with the exported function in a Nextjs app, which acts as an API page. The problem arises when the 'domainnames' array returns nothing in the 200 response. Interestingly, if I exclude the 'GetDomainStatus()' funct ...

How can we retrieve the isolated directive scope variable in the link function of AngularJS?

Check out the code snippet provided below. directive: app.directive("filterTree", function() { return { restrict: "AE", controller: function($scope, $http){ $scope.treeNodes = []; var filterItemsUrl = "/api/v1/ ...

Sorting customization within a complex nested array structure

Sorting a nested array can sometimes be tricky. Consider a JSON structure like the one shown below: var orders = [{ 'orderId': 1, 'sales': [{ 'salesNumbers': 3 }] }, { 'orderId': 2, ...

Transform the styles from a React component into Cascading Style Sheets

I have been tasked with transitioning all the styles from the JavaScript file to the CSS file while ensuring the design remains intact. I am facing an issue where using the CSS styles breaks the search field design. The original design can be seen here: S ...

The script ceases to function once the page is loaded from a JSON file

I'm facing an issue on my shopping website where the items and products are loaded from a JSON file. The problem is that once the page has loaded, the script fails to work properly. If the items take a little longer to load on the page, the script doe ...

How to properly format an HTML input box for numeric entry and ensure correct formatting of the minus sign

I need assistance with formatting an HTML text input box to only accept numeric values using JavaScript. Specifically, the input should allow digits, a minus sign, or a dot/comma (which will be converted to a dot). However, I want to prevent multiple conse ...

How can I trigger a drop-down menu to appear when an image is clicked on in the exact same location

As part of my website development project, I am working on a page that displays a list of customers in rows. Each customer row includes different fields such as priorities assigned by the MD and CEO. Depending on the priority value, an image is displayed. ...

Avoiding file storage of Json data

When scraping a page to gather information for saving in a file, I encountered an issue with writing the data in JSON using the "write-json" library from npm. The problem arises when trying to save all the data, as it stops at a certain point. Here is an e ...

Transmit ByteArray to JavaScript

Is there a way to send a jpg image as a ByteArray from ActionScript 3 to JavaScript? Additionally, how can one convert a ByteArray back into an image using JavaScript? ...

I'm interested in dynamically assigning colors with getorgchart

One situation I'm facing involves adding nodes to a root node depending on the response received from a REST service call. I want to set the color of the object's fill based on the "type" attribute of the nodes, which I'm setting from the R ...

What is the best way to contain the CSS for dynamically generated HTML within a div element without impacting other elements on the page?

I am currently facing a challenge where users can input any HTML into a text box, and I need to manipulate that HTML by identifying elements such as anchor tags or divs. To achieve this, I have created a hidden div and copied the pasted HTML into it using ...

The routing functionality in Angular4 encounters issues when the `router.navigate()` method is used within the callback of a

I am currently working on implementing Google Sign In within my Angular4 app, but I have run into an unusual issue with routing after using router.navigate() in the Google Sign In callback function. To help illustrate this issue, I have created a sample d ...

Generate a dynamic kendo dropdown with data sources assigned in separate methods

Creating a kendo dropdown list dynamically based on the number of received id's is presenting a challenge. A method has been implemented to loop through each id and generate a corresponding dropdown with that id. These dropdowns are not all generated ...

Is NextJS 13 the Key to App Directory On-Demand Revalidation?

I am looking to implement on-demand revalidation with next13 and the app directory. While I have successfully used the app-directory to replace the need for getServerSideProps or getStaticProps, there is one specific page on our site that needs to be rebui ...

Navigating through states in Angular-ui-router seamlessly while performing asynchronous calls

Attempting to initiate an asynchronous API call through the onEnter function to a new .state. onEnter: function(StatFactory){ StatFactory.getStats(function(res){ console.log("callback"); }); } What I h ...

methods for transforming a string into an object

let styleValues = "{ "background-color": "#4a90e2", "padding": 10px }"; JSON.parse(styleValues); The code snippet above triggers the error below: Uncaught SyntaxError: Unexpected token p in JSON at position 46 ...

When using @click as a link, it results in an

I'm attempting to create a clickable row in a datatable that functions as a link. Placing a standard <nuxt-link> within a <td> works fine, but wrapping the entire <tr> disrupts the table layout. Next, I tried using @click with a met ...

Accessing process.env in Nest.js controllers

Is there a way for me to access process.env.SOME_FIELD in nest.js? app.module.ts ... modules: [ ... ConfigModule.forRoot({ envFilePath: '.env.' + process.env.APP_CODE }), CatModule ... ] ... CatController.ts ...

AngularJS: Updating data in controller but not reflecting in the HTML view

Within my AngularJS app, I've come across the following code: example.html <div> <p>{{name}}</p> </div> <div> <button ng-click="someFunction()"></button> </div> exa ...