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

Deciding Between Promises and Callbacks in Node.js

As I update my older Node.js code, I am also creating new modules to integrate with the existing code. One challenge I face is transitioning from using callbacks to utilizing ES6 promises more frequently. This has created a mixture of functions that return ...

The value of the comment box with the ID $(CommentBoxId) is not being captured

When a user enters data in the comment box and clicks the corresponding submit button, I am successfully passing id, CompanyId, WorkId, and CommentBoxId to the code behind to update the record. However, I am encountering an issue as I also want to pass the ...

Using JavaScript to toggle the iron-collapse property

I've implemented multiple <iron-collapse> elements with unique IDs, each one corresponding to a <paper-icon-button>. On screens wider than 650px, I can interact with the <iron-collapse>s using their respective buttons. But on narrow ...

What could be the reason my code isn't successfully performing addition within the input field?

As a novice, I am practicing by attempting to retrieve a number from a text field, prompting the user to click a button that adds 2 to that number, and then displaying the result through HTML. However, I keep encountering an issue where NaN is returned whe ...

Retrieving information from dictionary in swift version 4

Currently, I am utilizing an API and trying to display its data in a table view. import UIKit import Alamofire class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { @IBOutlet weak var tableView: UITableView! @IBOu ...

What are the steps for aligning GeoJSON data with terrain within Cesium Sandcastle?

I am currently using terrain view in Cesium Sandcastle and have loaded roads data in GeoJSON format as lines. I would like to clamp them on the terrain, similar to this example (select "Sample line positions and draw with depth test disabled" from drop-dow ...

Rule: attribute should indicate a specific function

I am currently trying to implement the functionality from https://github.com/rpocklin/angular-scroll-animate in my project, but I keep encountering an error in my console: Error: Directive: angular-scroll-animate 'when-visible' attribute must ...

Simulated 'paths' configuration in non-TypeScript Node.js environment

In my TypeScript project, I've utilized a helpful configuration option in tsconfig.json that enables me to set up aliases for folders. { "compilerOptions": { "paths": { "@src/*": ["src/*"], "@imag ...

Is it possible for a Django view to send JSON data back upon a successful Ajax request?

I've tested both JsonResponse and HttpResponse (along with json.dumps), but even though ajax returns successfully, the returned JSON cannot be parsed by $.parseJSON(returned_json). I'm certain that the issue does not lie with parsing ($.parseJSO ...

Struggling to make even the most basic example work with TypeScript and npm modules

After stumbling upon this repository that made using npm modules within a Typescript program look easy, I decided to give it a try by forking it and making some changes. My goal was to add another package to get a better understanding of the process. So, I ...

Is there a variance in outcomes between constructing a pattern with a string and constructing a pattern with a regular expression "literal" in JavaScript?

Are there any distinctions between using RegExp literals versus strings? http://jsfiddle.net/yMMrk/ String.prototype.lastIndexOf = function(pattern) { pattern = pattern + "(?![\s\S]*" + pattern + ")"; var match = this.match(pattern); ...

java JSON responses containing long values that have been rounded

Upon receiving a JSON response from my RESTful service developed in Java, I have noticed that long data type values ending with 01 are being rounded down to 00. Allow me to provide examples: For instance, 12345123459876501 is returned as 1234512345987650 ...

Having trouble displaying the name and pricing

Can someone help me troubleshoot an issue with fetching data from this website? Here is the link . When I hit request to fetch the data, no data is being printed. import requests import time url = "https://www.adidas.com/api/metadata/pdp?" # ...

Develop a payment confirmation session using Stripe and Node.js

I have set up a POST request using Stripe to handle customer payments let paymentData = { errorMsg:'', key: process.env.STRIPE_PUBLIC_KEY } const session = await stripe.checkout.sessions.create({ payment_method_types: ...

Experiencing difficulties connecting with aspx while using Ext JS 4.2

Currently, I am facing an issue with making a call to an ASPX URL as the return keeps coming back as a failure. I have successfully used this URL in previous programming projects, but this is my first time utilizing it with Ext JS. Despite researching dif ...

The uniqueness validation with AJAX is not functioning properly within the Rails application

I'm currently working on validating the front end of my application. I've run into some problems with the ajax call I'm using to check if the user is entering a unique email. Here's my JavaScript code: function appendResults(data) { ...

Enhancing Javascript functionality with additional on.change customization opportunities

My website currently has a dynamic AJAX script that updates a table based on the selection from a dropdown menu with the ID of [id="afl_player_ID"]. However, I am looking to extend this functionality so that the same script runs when either [id="afl_playe ...

Deselect the checkbox that was initially selected when an alternative checkbox option has been chosen

I am trying to implement a feature where there are 2 groups of checkbox options on the same page. Below is the code snippet: <div class="col-xs-12"> <label class="checkbox-inline"> <input type="checkbox" th:field="*{borrowerRace1}" th:val ...

What steps can I take to prevent the [Vue warn]: Potential infinite update loop detected in a component render function issue in my VueJS project?

What are some tips to prevent an infinite update loop in a component render function using VUEJS? I have created a simple show password button with the following structure: <div class="mt-4 switchContainerGenPassword"> <div class="switchGene ...

Detach an item from its parent once it has been added to an array

Currently, I am facing an issue with a form on my blog. The blog is represented as an object that contains multiple content objects within it. I seem to be experiencing some confusion because the reactivity of the content I add to the Array persists with t ...