Data retrieval error: Google Charts Dashboard unable to fetch data from SQL database through AJAX call

I have been attempting to retrieve data from a SQL table that is generated daily through a stored procedure. The table consists of 4 columns.

My Ajax call retrieves the data and stores it in an array -

Array

Below is the code I am using to display the view and pass the array -

var chartData;

$(document).ready(function () {
    $.ajax({
        url: "/Reporting/LeaveList",
        data: "",
        dataType: "json",
        type: "POST",
        contentType: "application/json; chartset=utf-8",
        success: function (data) {
            //console.log(data);
            console.log(typeof data);
            chartData = data;
        },
        error: function () {
            alert("Error loading data! Please try again.");
        }
    }).done(function () {
        google.setOnLoadCallback(createTable);

    });
});

function createTable() {

    var data = new google.visualization.DataTable();


    data.addColumn('string', 'Date');
    data.addColumn('number', 'AnnualLeave');
    data.addColumn('number', 'Sick');
    data.addColumn('number', 'Total');
    data.addRow(chartData[0])


    // Create a dashboard.
    var dash_container = document.getElementById('dashboard_div'),
      myDashboard = new google.visualization.Dashboard(dash_container);

    // Create a date range slider
    var myDateSlider = new google.visualization.ControlWrapper({
        'controlType': 'ChartRangeFilter',
        'containerId': 'control_div',
        'options': {
            'filterColumnLabel': 'Date'
        }
    });

    // Table visualization
    var myTable = new google.visualization.ChartWrapper({
        'chartType': 'Table',
        'containerId': 'table_div'
    });

    // Bind myTable to the dashboard, and to the controls
    // this will make sure our table is update when our date changes
    myDashboard.bind(myDateSlider, myTable);

    // Line chart visualization
    var myLine = new google.visualization.ChartWrapper({
        'chartType': 'LineChart',
        'containerId': 'line_div',
    });

    // Bind myLine to the dashboard, and to the controls

    myDashboard.bind(myDateSlider, myLine);

    myDashboard.draw(data);

And here is a snippet from the controller -

data = (
                from u in db.StaffReportingDay
                select new StaffReportingDayVM
                {
                    Date = u.Date.ToString(),
                    AnnualLeave = u.AnnualLeave,
                    CompassionateLeave = u.CompassionateLeave,
                    Sick = u.Sick,
                    StudyLeave = u.StudyLeave,
                    Total = u.Total
                }).ToList();
                }


        var ChartOne = new object[data.Count + 1];
        ChartOne[0] = new object[]
        {
            "Date",
            "Annual Leave",
            "Sick Leave",
            "Total on Leave"
        };

        int j = 0;

        foreach(var i in data)
        {
            j++;
            ChartOne[j] = new object[] {i.Date.ToString(), i.AnnualLeave, i.Sick, i.Total };
        }


        return Json(ChartOne, JsonRequestBehavior.AllowGet);

I am facing an issue where the array is not being pulled into the view, instead I receive an error message:

Uncaught Error: Type mismatch. Value Annual Leave does not match type number in column index 1

Despite trying different approaches, I am seeking advice and insights from other individuals. Your input would be greatly appreciated.

Answer №1

Resolved using the following code:

 function generateChart() {
    var info = new google.visualization.DataTable();
    info.addColumn('date', 'Date');
    info.addColumn('number', 'VacationDays');
    info.addColumn('number', 'PersonalDays');
    info.addColumn('number', 'SickDays');
    info.addColumn('number', 'TotalDays');
    $.each(dataPoints, function (i, point) {
        info.addRow([
          (new Date(point.Date)),
          parseFloat(point.VacationDays),
          parseFloat(point.PersonalDays),
          parseFloat(point.SickDays),
          parseFloat(point.TotalDays)
        ]);
    });

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

The res.download() function is not functioning properly when called from within a function, yet it works perfectly when directly called through the API in a browser

I have a button that, when clicked, triggers the downloadFile function which contacts the backend to download a file. async downloadFile(name) { await this.$axios.$get(process.env.API_LINK + '/api/files/' + name) }, app.get('/api/files/ ...

Showing perspectives that include 'partial'/'nested' components in EXTjs 4

I am struggling to comprehend how I should define and implement the MVC model for my test application in EXTjs4. Let's take a look at the structure below. app.js Ext.application({ name: 'AM', appFolder: 'app', control ...

Combining JSON arrays by utilizing a shared entry

My Python script fetches two JSON arrays using the Get API Data Set 1: {'result': [ {'number': '0010041', 'month': 'January'}, {'number': '0010042', 'month': 'M ...

Tips on saving a cookie using universal-cookie

I followed a solution on Stack Overflow to set a cookie in my React application. However, the cookie expires with the session. Is there a way I can make this cookie persist beyond the session so it remains even when the browser is closed and reopened? ex ...

Effective method for combining two arrays into one with distinct values

I have two arrays that look like this array ( [0] => Array ( [search_terms] => Big Black Gay [searches] => 1 ) [1] => Array ( [search_terms] => Men Seeking Men Personals [searches] => 1 ) ...

How to fetch database results using jQuery AJAX and PHP's JSON encoding

I am currently working on a PHP code that is triggered using jQuery AJAX to query a database and retrieve results, which are then encoded into JSON format. //$rows is another query foreach($rows as $row) { $sql = 'SELECT field1, field2 FROM tabl ...

Understanding the inner workings of encapsulation in TypeScript

I'm diving into the world of encapsulation in Typescript and stumbled upon an example that has left me scratching my head. I am confused as to why I can access and modify the private members of a specific class directly. class Encapsulate { str:s ...

Detecting the Enter key press with jQuery event.keyCode

My combo box is filled with values, and I want to allow the user to select a value by pressing the Enter key. The user can navigate using the Arrow keys. To select a value, the user should press the Enter key. I attempted the following code: $('#c ...

Minimize the amount of ajax requests for quick search functionality

Currently, I am in the process of developing an instant search drop down feature for my website. Everything seems to be functioning correctly except for this particular issue. var timeOut; $('#search input[name=\'search\']'). ...

Updated the object in an array retrieved from an API by adding a new key-value pair. Attempted to toggle the key value afterwards, only to find that

Essentially, I am retrieving products from an API and including a new key value isAdded in the object within the products array. I utilized a foreach loop to add that key and it was successfully added. Now, when I click the Add to cart button, the product ...

How can I assign a randomly selected item from a string array to a variable in Java?

Having recently started learning Java, I've been struggling to find a clear answer from my college lecturer. Sorry if this question seems silly, but I need help with creating a level up screen for an assignment that involves using an array. I have se ...

Issues with activating jquery toggle function

Could someone help me figure out why this code isn't functioning as expected? HTML <head> <body id="top" class="home page page-id-1412 page-template-default logged-in stretched open_sans open_sans siteorigin-panels" itemtype="http://schema ...

What is the best way to eliminate the border of an expansion panel in Material-UI?

Is there a way to eliminate the border surrounding the expansion panel in Material-UI? ...

Creating tube-like geometry in intervals using three.js

Is there a way in Tube Geometry(Three.js) to plot and render only a portion of the tube at a time, with the option to continue plotting from that point after a set interval or timer? ...

The Ajax url fails to load when the domain is entered with "www" at the start of the URL

I have very little experience with ajax, but I am currently using a plugin on my website that relies on ajax functions to check for installation and populate content. My issue arises when accessing the website using different URL formats - without www, i ...

Incorrect encoding in AJAX

I'm encountering a problem with the incorrect encoding being transmitted through AJAX. Here is my code: $(document).ready(function(){ $.ajax({ type: "POST", url: "server_save.php", contentType: "applicati ...

Creating Location-Specific Customer Data using AngularJS similar to Google Analytics

Looking to create a user registration map similar to Google Analytics without actually using Google Analytics. Can anyone provide assistance with this task? I am utilizing MVC, C#, Sql Server-2014, AngularJS, and jQuery for this project. Despite my efforts ...

typescript: best practices for typing key and value parameters in the forEach loop of Object.entries()

I have a specific object with key/value pairs that I need to iterate over using the entries() method of Object followed by a forEach() method of Array. However, I'm struggling to understand how to avoid a typescript error in this situation: type objTy ...

Symfony/encore requires devDependencies in order to successfully compile

My experience with Symfony5 and encore has been smooth until I attempted to deploy to production. In order to install dependencies, you can use the command npm install --production. To compile, run npm run build --prod. I encountered an issue when trying ...

Navigate to specific element from bootstrap navigation bar

I am in the process of creating a website for a small organization. The website is being constructed using bootstrap 4, and there is a navbar that connects to various flex-containers. I want these connections to smoothly scroll to their respective elements ...