Is it possible to create a pie chart using Chart.js with data fetched through an Ajax HTTP GET

Embarking on a new journey here, this week's focus is on delving into Chartjs for canvas and brushing up on JSON usage. The task at hand includes employing an Ajax HTTP GET request to fetch the json file. However, I am currently stumped on how to trigger the function that populates the data and renders the pie and bar charts. Assistance from anyone in the know would be greatly appreciated.

HTML Code

<canvas id="pieChart" width="400" height="400"></canvas>

    <!-- Scripts -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="js/Chart.js"></script>
<script src="js/js.js"></script>

JS

    $(function () { 
    getPieChartData(); 
}); 


function getPieChartData() { 
    $.get( 
        'http://localhost:8888/r_tomino_assignment6/data/piechart-data.json', 
        function (data) { 
            displayPieChart(data) 
        }, 
        'json' 
        ); 
} 

var context = document.getElementById("pieChart").getContext("2d");   
var myPieChart = new Chart(context).Pie(data);

JSON Data

    [
    {
        "color": "#F7464A",
        "highlight": "#FF5A5E",
        "label": "Red",
        "value": 300
    },
    {
        "color": "#46BFBD",
        "highlight": "#5AD3D1",
        "label": "Green",
        "value": 50
    },
    {
        "color": "#FDB45C",
        "highlight": "#FFC870",
        "label": "Yellow",
        "value": 100
    }
];

Answer №1

Have you checked if your displayPieChart function is being called? It seems like it has not been defined anywhere in your code. Since the AJAX request is asynchronous, you need to provide it with a callback function, which you already have. All you need now is another function named displayPieChart that takes the data and generates the chart.

This new function should then proceed to execute the following lines:

var context = document.getElementById("pieChart").getContext("2d");
var myPieChart = new Chart(context).Pie(data);

For example:

function displayPieChart(data) {
    var context = document.getElementById("pieChart").getContext("2d");   
    var myPieChart = new Chart(context).Pie(data);
}

This will allow you to visualize your data effectively.

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

Vue Eslint Extension

My current project utilizes the eslint vue plugin with specific rules set in place. "rules": { "vue/html-closing-bracket-newline": ["error", { "singleline": "never", "multiline": "always" }], "vue/html-closi ...

Step-by-step guide to troubleshoot and resolve nodeJS PUT route issue when updating an incorrect ID

Attempting to update an object with the wrong ID using the PUT route. I attempted to switch from params.id to body.id, but it didn't alter the output as expected. The update is only affecting the first object ever created, which does not correspond t ...

Using a Python list as an argument in a JavaScript function

How can I pass a python list as an argument to a JS function? Every time I attempt it, I encounter the error message "unterminated string literal". I'm baffled as to what's causing this issue. Here is my python code (.py file): request.filter+= ...

Is there a way to send a variable to PHP and execute it on the current page?

I need to integrate an inventory search feature on a local clothing store's website. The challenge lies in setting up the PHP script that pulls and organizes the data to run on the same page as the search form itself. Given my limited experience with ...

Highcharts-ng allows us to create charts without using the traditional syntax such as $('#container').high

After setting up the chart's configuration in my controller, I am facing an issue. The HighCharts-ng (an angularJS directive for HighCharts) has a method that I want to implement: $scope.ohlcChartConfig = { options: {....... I ne ...

Using codedeploy to deploy a Next.js application onto an AWS EC2 instance

After creating a fresh NextJS app with only basic boilerplate files and folders, I uploaded it to a CodeCommit repository. I already had a functional CodePipeline and simply switched the Source stages. However, I am encountering deployment failures during ...

Error: The requested collection# cannot be found in the Node.js Express routing system

Recently, I have started learning nodejs and implemented a simple API that allows users to log in with passport and then redirects them to the /collections route. While this part is functioning correctly, I am encountering issues with POST requests which a ...

Validating checkboxes using HTML5

When it comes to HTML5 form validation, there are some limitations. For instance, if you have multiple groups of checkboxes and at least one checkbox in each group needs to be checked, the built-in validation may fall short. This is where I encountered an ...

Issues encountered while trying to access a child state using Ionic and UI-Router

My current setup includes the following parent states: // Abstract state for tabs directive .state('tab', { url: "/tab", abstract: true, templateUrl: "templates/tabs.html", controller: "TabCtrl" }) // Each tab has its ow ...

The NextJS i18n feature is encountering an issue with the locale being undefined

Currently, I'm in the process of transitioning my website to NextJS, and I've run into some difficulties with internationalization. Even though I'm following the steps outlined in the official documentation, the locale displayed in the insp ...

Tips on customizing the MSAL login commands for successful integration with numerous users

Successfully implemented the code to login using a username and password combination with Cypress for a webapp integrated with MSAL. In the end-to-end Testfile: describe('Login with MSAL as xxUsername', () => { beforeEach(() => { cy.Lo ...

Hmm, JavaScript is throwing a JSON parse error related to single quotes. But where exactly is

When using an upload php script with AS3 and now with JavaScript, I encountered a test feature that should return this if everything is okay: {"erro":"OK","msg":"","descr":"op:ini,urlArq:\/Library\/WebServer\/Documents\/www\/sintr ...

Dividing a pair of CSS stylesheets on a single HTML page

Currently, I am working on a HTML page that includes multiple javascripts and css files in the header section. <link href="@Url.Content("~/Content/css/main.css")" rel="stylesheet" type="text/css" /> In order to make the website mobile-friendly, I s ...

A technique, such as regular expressions, can be used to detect the quantity of newline characters in the text entered by the user in a text area

I'm trying to figure out how to count the number of newline characters (or whatever is inserted when the user presses the return key) in a textarea's value. I believe I should be using a regular expression for this task, but I'm not very ski ...

Express.js receiving JSON POST data with AngularJS incorrectly interpreted as keys instead of values

I am facing an issue while trying to make a POST request with JSON data from angularjs to node/express. The problem is that all the data is appearing in the KEY of the req.body instead of as key value pairs. Although I found a similar question addressing ...

After being redirected from another page using history() in React, the state is initially set to null but later gets updated to the correct value - Firebase integration

After logging in and being redirected to the profile page, I encounter an error that says 'Unhandled Rejection (TypeError): Cannot read property 'email' of null'. How can I ensure that the state is set before proceeding with any additio ...

What is the best way to receive a notification when a user chooses any option in a Material UI Autocomplete React component?

My dilemma involves using an autocomplete feature that doesn't behave as expected. I am looking to detect when an option is selected, regardless of whether it's the same as the last selection. The onChange event I'm using only triggers if th ...

Error encountered: jquery form validation fails to register changes

I am currently developing a calculator-like code where users will submit a form multiple times, and I need to save the result of calculations only if there are changes in the form. For instance, when a user clicks the "Calculate" button for the first time, ...

Insert an element into a JSON collection

I am currently working on a JavaScript function that utilizes an ajax call to retrieve data from an API in the form of a JSON array. Here is a snippet of the array structure that I receive: [ { "ErrorType": "Errors", "Explanations": [ { ...

What is the best way to send data to PHP while moving objects between different div elements?

I have a situation where I have two parent divs containing dynamic children divs, and I want to enable POST requests to PHP when items are dragged from one side to the other (and vice versa). Here is the Javascript code I am using: function allowDrop( ...