Using Javascript to fetch undefined data from a C# backend with AJAX

I am struggling to create a web page using Google charts. I attempted to build it with C# as a web form and retrieve data from a local database to JavaScript. However, I keep receiving an error stating that the data is undefined in the response from Ajax. This is the C# code snippet:

        [WebMethod]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public static object[] GetChartData()
    {
        List<GoogleChartData> data = new List<GoogleChartData>();
        //MyDatabaseEntities is our dbContext
        using (MyDatabaseEntities dc = new MyDatabaseEntities())
        {
            data = dc.GoogleChartDatas.ToList();
        }
        var chartData = new object[data.Count + 1];
        chartData[0] = new object[]{
                "Product Category",
                "Revenue Amount"
            };
        int j = 0;
        foreach (var i in data)
        {
            j++;
            chartData[j] = new object[] { i.Product_Category, i.RevenueAmount };
        }return chartData;
    }

The JavaScript code looks like this:

        <asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="server">
<!-- Javascript Job-->
<script src="Scripts/jquery-1.10.2.js"></script>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script>
    var chartData; // global variable to store chart data
    google.load("visualization", "1", { packages: ["corechart"] });

    // Fetching data for chartData

    $(document).ready(function () {

        $.ajax({
            url: "GoogleChart.aspx/GetChartData",
            data: "",
            dataType: "json",
            type: "post",
            contentType: "application/json; charset=utf-8",
            success: function (data) {
                chartData = data.d;
                alert(chartData);
            },
            error: function () {
                alert("Error loading data! Please try again.");
            }
        }).done(function () {
            // once data is loaded completely
            google.setOnLoadCallback(drawChart);
            drawChart();
        });
    });


    function drawChart() {
        var data = google.visualization.arrayToDataTable(chartData);

        var options = {
            title: "Company Revenue",
            pointSize: 5
        };

        var pieChart = new google.visualization.PieChart(document.getElementById('chart_div'));
        pieChart.draw(data, options);

    }

</script>
<div id="chart" style="width: 500px; height: 400px">
</div>

Here is a picture of the database structure.

Can someone please guide me on how to fetch table data via Ajax and display it in a chart?

Answer №1

It is advisable to avoid using the jsapi method for loading the Google Charts library as per the latest release notes.

The version of Google Charts accessible through the jsapi loader is no longer receiving consistent updates. It is recommended to switch to the new gstatic loader (loader.js) going forward.

<script src="https://www.gstatic.com/charts/loader.js"></script>

This change will primarily affect the load statement...

google.charts.load('current', {
  callback: drawChart,
  packages: ['corechart']
});

As demonstrated above, the callback can be specified within the load statement

The callback function will signal when Google Charts has finished loading, in conjunction with the DOM

Hence, there is no necessity for utilizing setOnLoadCallback or $(document).ready

In terms of the setup process, it is recommended to use the following configuration...

<asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="server">
<!-- JavaScript Section-->
<script src="Scripts/jquery-1.10.2.js"></script>
<script src="https://www.gstatic.com/charts/loader.js"></script>
<script>
    google.charts.load('current', {
      callback: drawChart,
      packages: ['corechart']
    });

    function drawChart() {
      $.ajax({
        url: "GoogleChart.aspx/GetChartData",
        data: "",
        dataType: "json",
        type: "post",
        contentType: "application/json; charset=utf-8",
      }).done(function (data) {
        var chartData = google.visualization.arrayToDataTable(data.d);
        var options = {
          title: "Company Revenue",
          pointSize: 5
        };
        var pieChart = new google.visualization.PieChart(document.getElementById('chart_div'));
        pieChart.draw(chartData, options);
      }).fail(function (jqXHR, textStatus, errorThrown) {
        console.log("Error: " + errorThrown);
      });
    }
</script>
<div id="chart" style="width: 500px; height: 400px">
</div>

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

Using ng-repeat to iterate over forms in AngularJS

I have implemented dynamic forms using the ng-repeat directive where form fields are generated based on the userid value. The requirement is that the add user button should be enabled only when all form fields are filled. However, currently the button rema ...

Tips for achieving proper styling and formatting of elements in jQuery UI

I've encountered an issue when trying to use jQuery UI after downloading it multiple times. In the examples provided with the download, the UI elements appear perfectly formatted, but when I implement them on my own pages, the styles and formatting ge ...

What techniques can be applied to utilize JSON data in order to dynamically create menu components using the map method?

My current challenge involves dynamically generating a set of menu items using data retrieved from a JSON file. I've attempted to achieve this by mapping the values with props, but it seems like I'm overlooking something. Below is the code snipp ...

The form is refusing to submit even after using the "return false

Even after adding validation to the form, it still submits when the script returns false. The Form Submission <form action=payment.php method=POST name=UserForm id=UserForm onsubmit="return check(this); return false;"> Javascript Code function ch ...

Ensuring the image is properly sized to fit the screen and enabling the default zoom functionality

I am looking to achieve a specific behavior with an image, where it fits the viewport while maintaining its aspect ratio and allowing for zooming similar to how Chrome or Firefox handle local images. Here are the details of my project: The image I have is ...

What other options are available besides componentDidUpdate for retrieving the chosen date from a date picker and including it in an API request?

Currently, I am utilizing react-dates to implement a datepicker feature. Whenever the user modifies the date, it updates a prop that is then sent to the backend as a parameter in a query to fetch specific results for that particular day from the database. ...

Galleriffic 2.0: Enhancing Animation Queues

I'm currently exploring how to utilize the stop() function in order to halt the animation buildup within Galleriffic. This issue arises when swiftly and repeatedly mousing over the thumbnail images. While I understand that in a basic jQuery script, yo ...

Non-Mozilla browsers facing progress dialog block due to AJAX async:false

My shopping cart provider recently made a temporary fix by adding "async:false" to the cart calculation code in order to prevent potential issues with AJAX call completion. However, this caused an unintended consequence of preventing a jquery progress dial ...

Controlling hover effects with Material-UI in a programmatic way

I have integrated the following Material-UI component into my application: const handleSetActive = _spyOn => { linkEl.current.focus(); }; const linkEl = useRef(null); return ( <ListItem button component={SmoothScrollLink} t ...

Looking for reliable resources on establishing a connection between a Google account and my application

I am currently working on creating a react native app that aims to simplify the user login process by allowing them to link their Google account with just one click. This way, users won't have to constantly log in every time they use the app. While I ...

Working with arrays of objects in D3.js using Javascript

Seeking guidance as I navigate through the world of javascript and D3.js. I have two distinct data sets (arrays of objects) that I hope to merge. My goal is to align the National Average Scores with the State Average Scores by matching the 'Answer&ap ...

What causes the appearance of 'GET/ 304 --' in my code? (vue.js, express)

While attempting to fetch data on the client-side using axios in vue.js, I encountered a server-side error with the code 'GET/ 304 --' The reason for this occurrence is unclear to me and I am unsure of how to troubleshoot or resolve it. If I re ...

Is there a way to alter the color of an item just by clicking on it?

Looking to enhance my programming skills, I am interested in changing the color of an item to a series of colors upon clicking. I am weighing the options between CSS, javascript, and JQuery to achieve this effect. Which approach would be the most optimal ...

Attempting to Gain Dominance While Performing an Insert Operation in RadGrid

I have a basic layout for showcasing comments in a grid. Below is the GridBoundColumn setup; <telerik:GridBoundColumn DataField="Comment" ...

Launching my initial React application

After creating a small React app using the boilerplate available at https://github.com/vasanthk/react-es6-webpack-boilerplate I was able to run it smoothly on my localhost. However, I am now facing confusion on how to configure it for live deployment. F ...

Is it possible to save user inputs in a .json file for future use, and retrieve and reuse them in subsequent sessions or processes?

I am currently developing an account generator using puppeteer and I have a specific requirement for user inputs. The script prompts the user to input necessary variables, but I am interested in exploring the possibility of storing these inputs in a JSON ...

Sharing package JSON file dependencies with child engines and addons in Ember.js

I am seeking information on how Ember Js can share the parent app's package.json file dependency (xyz:3.0.0) with child engines and addons without them needing to redeclare the dependencies in their own package.json files. This is to reduce the overal ...

Downloading a PDF file received from a Django view using JavaScript and jQuery

I have a celery task that creates PDF files on the click of a button. When the button is clicked, the JavaScript side will keep checking until the task is done, and when it is, it will download the file. Some recursion should do the trick: $(".getPdf").o ...

Here are the steps to divide an array of objects into separate objects based on their keys

The data I currently have is formatted like this: [{ "Consumer": [{ "Associated ID": "JSUDB2LXXX / BIC 7503 / US", "Parent Consumer": "7503" }], "Owner": [{ &qu ...

Defining data types in MongoDB is an essential part of database management

Creating a C# project for a bakery chain to track every make, including ingredients and recipes, presents a challenge for someone like me with experience in SQL. The idea of using MongoDB crossed my mind. As I began to set up the Type, database interface, ...