The essential guide to coding Javascript/Ajax in conjunction with Chart.js

I have successfully implemented a controller action in my MVC project that generates a JSON record with the required components. The challenge I am facing now is integrating this data into a pie chart using chart.js. The pie chart should display the counts of related countries based on the JSON data retrieved. Initially, I had set up the visualization using Google Visualization, but now I prefer to utilize chart.js which I recently started using. While creating charts with static data poses no problem, fetching data from a SQL table, converting it to JSON, and reading from it has proven to be more challenging.

I attempted to use a similar structure to access the data using data[], but that did not yield the desired results. I also tried referencing the data as getData, which is a variable for the AJAX function. However, I am still unable to retrieve the data successfully and it only appears after a page refresh.

Below is the controller action:

public ActionResult CustomersByCountry()
{
    CustomerEntities _context = new CustomerEntities();

    var customerByCountry = (from c in _context.Addresses
                             group c by c.Country into g
                             orderby g.Count() descending
                             select new
                             {
                                 Country = g.Key,
                                 CountCustomer = g.Count()
                             }).ToList();

    return Json(new { result = customerByCountry }, JsonRequestBehavior.AllowGet);
}

And here is the JavaScript/AJAX code, nested within a document.ready function along with other charts:

EDIT - Revised AJAX code, but still not functioning as intended

OrdersByCountry()

function OrdersByCountry() {
    $.ajax({
        url: '/admin/CustomersByCountry',
        method: "GET",
        dataType: "json",
        error: function (_, err) {
            console.log(_, err)
        },
        success: function (data) {
            console.log (data);
            var customer = $("#customerByCountryPieChart").get(0).getContext("2d");
            console.log(customer)
            var cpieChart = new Chart(customer, {
                type: 'pie',
                data: data,
                options: {
                    responsive: true,
                    title: {
                        display: true,
                        text: "Customers By Country",
                    }
                }
            });
        }
    });
};

EDIT - The updated code that is now functional:

I decided to fetch states instead of country to avoid any confusion. It made more sense to retrieve states rather than countries at this stage. Although the graph is now displaying correctly, I still need to refine the labels and other details.

OrdersByStates()

function OrdersByStates() {

    $.ajax({
        url: '@Url.Action("CustomersByStates", "Admin")',
        data: JSON,
        contentType: "application/json; charset=utf-8",
        method: "get",
        dataType: "json",
        error: function (_, err) {
            console.log(_, err)
        },
        success: function (response) {
            console.log(response);
            var jsonresult = response

            var labels = jsonresult.result.map(function (e) {
                return e.State;
            });
            var data = jsonresult.result.map(function (e) {
                return e.CountCustomer;
            });;

            var ctx = document.getElementById("CustomerByStatePieChart").getContext("2d");
            var cpieChart = new Chart(ctx, {
                type: 'pie',
                data:
                {
                    datasets: [
                        {
                            backgroundColor: ["#46BFBD", "#F7464A"],
                            hoverBackgroundColor: ["#5AD3D1", "#FF5A5E"],
                            label: "Orders",
                            data: data,
                        }]
                },
                options: {
                    responsive: true,
                    title: {
                        display: true,
                        text: "Customers By Country",
                    }
                }
            });

        }
    });
};

});

Answer №1

attempting:

let pieChart = new Chart(client, {
                   type: 'pie',
                   data: data.response,
                   options: {
                       responsive: true,
                       title: {
                           display: true,
                           text: "Client Distribution By Country",
                       }
                   }
               });

the data received from the server in response to your query is {response: LIST}

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

Issue with ReactiveVar causing React component not to re-render

I am a beginner with React in Meteor. To summarize: When I change the value of my ReactiveVar in my data container, the view does not update. Here is the code snippet: import React, { Component, PropTypes } from 'react'; import ReactDOM from & ...

What is the best method for retaining the complete YQL outcome within a JavaScript object?

I am trying to store the output of my YQL Query in a JavaScript object Here is my query: SELECT * FROM html WHERE url="http://myurl.com" and xpath="/html/body/center/table[1]/tr" Can someone guide me on how to proceed? I have gone through the YQL docu ...

React useEffect only retrieves the last element of an array object

I am facing an issue where React seems to only save the last element in my array. Even though I have two elements, when mapping over them, only the last element is being placed in the hook each time. React.useEffect(() => { if (bearbeiten) { handleCli ...

What is the process for browserifying the net.Socket module in Node.js?

I'm exploring ways to connect and query my MS SQL database from JavaScript in a web browser (specifically Chrome, not IE as I don't want to use ActiveX controls). I came across this Node library called Tedious and Browserify to help with this tas ...

Attempting to resolve an error message with the help of JQuery

I need help figuring out how to clear an error icon when a user presses a key. ** EDIT - including the HTML code ** <input class="validate" type="text" data-type="string" id="address" /> <input class=" ...

Utilize Java to extract information from a JSON file

I am currently attempting to navigate through a JSON file using Java, but unfortunately I've hit a snag due to the complex structure of the file. If you want to take a look at the file yourself, you can download it here: Reddit JSON file Specificall ...

Is there a way to ensure the req.body retrieved from a form is not undefined?

Every time I submit a form with information, the response comes back as undefined. I have provided the code below for reference. If I include the (enctype="multipart/form-data") in the form, I do not receive any data in the body (req.body). However, if I e ...

Using Ajax with Controller Action in Yii2

As a newcomer to programming, I am facing an issue where I need to call a function when the user inputs data and clicks the submit button. Although I am working with Yii2, I lack experience in Ajax. Despite my efforts, the controller action is not being tr ...

How to achieve a typewriter effect in React using JavaScript

I've been attempting to incorporate a typewriter effect into my website - at the moment, the animation is functioning but each letter appears twice (e.g. instead of reading "Welcome!" it displays "Wweellccoommee!!"). I suspect this is an asynchronous ...

Passing props from a parent component to a nested child component in Vue 3

My goal is to achieve the functionality described in the title. Suppose I have the following structure: parent -> child -> secondChild Currently, there is a variable called isActive in the parent component. Below is how it can be implemented: paren ...

Optimizing image centering in Next JS as screen size expands

I've been struggling to work with NextJS's Image component. My goal is to set up a banner image that only covers a specific amount of space on the screen, regardless of screen size. I have managed to achieve this by using max-height: 30vh and ov ...

The Material UI Rating Component is malfunctioning and showing an incorrect value

I'm currently working on a component loop that takes in async data. Everything is rendering properly except for the first component, where the Rating component isn't displaying its value correctly (it just shows 0 stars). Here's the code: & ...

Prevent altering client values via developer tools

Our application is built using HTML5, the Foundation framework by ZURB, and AngularJS. We are seeking a way to prevent users from accessing and changing the values of our Angular objects (specifically scope variables) through the developer tool console. ...

Attempting to send form data to a servlet through JQuery

I'm trying to send data to a servlet for insertion into a MySQL database. Below is the HTML form: <form id="commentForm" name="commentForm" action="http://server.co.uk/dbh" method="POST"> <input type="text" name="name" placeholder="Your ...

How to specify a single kind of JavaScript object using Typescript

Let's say we have an object structured as follows: const obj = [ { createdAt: "2022-10-25T08:06:29.392Z", updatedAt: "2022-10-25T08:06:29.392Z"}, { createdAt: "2022-10-25T08:06:29.392Z", animal: "cat"} ] We ...

Sequence of promises: The parent promise does not wait for the child promise to be executed before moving on

I am retrieving data from a particular mongoDB collection. Within that response, I obtain the ID associated with another collection's data and merge it into one cohesive object. Take a look at my code snippet below. It seems like it's not waitin ...

Develop an ASCX component to handle various tasks

I am currently in the process of developing a unique custom control that will feature two radio buttons. This project is being carried out using MVC4 and ASP.NET technology. At the moment, I have successfully created two sets of two radio buttons on separa ...

The task of mapping an array of objects with nested values using JavaScript is proving to

Attempting to convert an array of objects with nested values in child objects like: const objs = [{ "B": { "value": 1, }, "D": { "value": "45" }, "E": { "value": "234" }, ...

Sender receives a response from Socket.io

My goal is to have a socket respond only to the sender. Currently, I am working on having the user connect to the server using JavaScript when they visit any webpage. However, I am unsure whether the connection will be reset each time the user reloads th ...

Retrieving Information from JSON File Using a Variable (JavaScript/Discord.js)

While I was coding my Discord bot, I encountered an unexpected issue. Normally, after linking a JSON file, you can access data by using jsonFile.path to retrieve specific information. However, I faced a challenge where I needed to replace the path with a ...