What are the steps to integrate dynamic data into chartjs?

Can you assist me in understanding how to dynamically populate Chartjs with data from a json file? Specifically, I am looking to dynamically fill the labels and data fields.

Sample JSON File <<<

[
   {
      "EFICAZ_TAB_ITEM_ID":1,
      "EFICAZ_PERCENTS":99
   },
   {
      "EFICAZ_TAB_ITEM_ID":2,
      "EFICAZ_PERCENTS":99
   },
   {
      "EFICAZ_TAB_ITEM_ID":3,
      "EFICAZ_PERCENTS":99
   }
]


CHARTJS Setup <<<

var ctx = document.getElementById('myChart').getContext('2d');
var chart = new Chart(ctx, {
    // The type of chart we want to create
    type: 'line',

    // The data for our dataset
    data: {
        labels: [???],
        datasets: [{
            label: "My First dataset",
            backgroundColor: 'rgb(255, 99, 132)',
            borderColor: 'rgb(255, 99, 132)',
            data: [???],
        }]
    },

    // Configuration options go here
    options: {}
});

Answer №1

I utilized the $.ajax() method to retrieve JSON data and store it in two arrays that can be used for labeling and data in a chart. Hopefully, this solution proves helpful for you!

 var labelsArray = [];
    var dataArray = [];

    $.ajax({
      url: "test.json",
      dataType: 'json',
      async: false,
      success: function(data) {
        $.each(data, function(i, field){
             labelsArray.push(field.EFICAZ_TAB_ITEM_ID);
             dataArray.push(field.EFICAZ_PERCENTS);
           });
      }
    });

     $.getJSON("test.json", function(result){
           $.each(result, function(i, field){
             labelsArray.push(field.EFICAZ_TAB_ITEM_ID);
             dataArray.push(field.EFICAZ_PERCENTS);
           });
        });

    var ctx = document.getElementById("myCanvas").getContext('2d');

    var chart = new Chart(ctx, {
        type: 'line',
        data: {
            labels: labelsArray,
            datasets: [{
                label: "My First dataset",
                backgroundColor: 'rgb(255, 99, 132)',
                borderColor: 'rgb(255, 99, 132)',
                data: dataArray,
            }]
        },
        options: {}
    });

Answer №2

Check out this code snippet for creating a dynamic chart using Chart.js:

document.addEventListener('DOMContentLoaded', function(){
  
    var chartData = [
      {
        "EFICAZ_TAB_ITEM_ID":1,
        "EFICAZ_PERCENTS":21
      },
      {
        "EFICAZ_TAB_ITEM_ID":2,
        "EFICAZ_PERCENTS":55
      },
      {
        "EFICAZ_TAB_ITEM_ID":3,
        "EFICAZ_PERCENTS":32
      }
    ];
    
    var labels = [];
    var values = [];
    chartData.forEach(function(el, key){
      labels.push(el.EFICAZ_TAB_ITEM_ID);
      values.push(el.EFICAZ_PERCENTS);
    });
    
    var ctx = document.getElementById('myChart').getContext('2d');
    var chart = new Chart(ctx, {
        type: 'line',
        data: {
            labels: labels,
            datasets: [{
                label: "My First dataset",
                backgroundColor: 'rgb(255, 99, 132)',
                borderColor: 'rgb(255, 99, 132)',
                data: values,
            }]
        },
        options: {}
    });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.min.js"></script>
<canvas id="myChart" width="400" height="200"></canvas>

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

Warning: Unhandled promise rejection occurred while running the test

Currently delving into the world of selenium with a focus on testing the registration page. I've crafted a registration page class equipped with methods for monitoring registrations. However, upon attempting to execute a test within the application cl ...

Eliminating pins from Biostall Google Maps plugin in CodeIgniter

After successfully setting up the Biostall Google Maps for Codeigniter, I am now looking to remove specific markers using ajax. The JavaScript code being executed is as follows: var myLatlng = new google.maps.LatLng(53.236114, 6.496444); var markerOption ...

How can one utilize Codemirror code folding while avoiding the use of "[ ]"?

I am looking forward to implementing Codemirror codefolding for folding only braces { and }, as well as comments. However, I am facing an issue where it also folds square brackets [ and ]. Since square brackets are usually part of one-line statements, I do ...

Why is my JSON object showing up as undefined in my Node.js POST request?

I have a CentOS server that is currently running a node.js HTTP server (code provided below). My goal is to pass JSON data from the command line by using the following CURL command: curl -X POST -H "application/json" -d '{"val1":"hello","val2":"my"," ...

Having trouble getting my local website to load the CSS stylesheet through Express and Node.js in my browser

https://i.stack.imgur.com/qpsQI.png https://i.stack.imgur.com/l3wAJ.png Here is the app.js screenshot: https://i.stack.imgur.com/l3wAJ.png I have experimented with different combinations of href and express.static(""); addresses. However, I am ...

Issue with posting data to a JSON file using Vue and axios

I am encountering an issue with axis posting to a local .json file. The error I am receiving is: POST http://localhost:8080/todolist.json 404 (Not Found) TodoListEditor.vue?b9d6:110 Error: Request failed with status code 404 at createError (createErr ...

Guide on retrieving data parameter on the receiving page from Ajax response call

I am working on dynamically opening a page using Ajax to avoid refreshing the browser. The page opens and runs scripts on the destination page, but before running the script, I need to retrieve parameters similar to request.querystring in JavaScript. Belo ...

Take a sequence of multiple words and combine them into a single string with hyphens in between

I've been working on a WordPress website and I created a JavaScript function that adds a class to the body tag, allowing for different backgrounds based on the category. It works perfectly fine when the category is a single word, but encounters issues ...

Is there a more effective method to return a response apart from using a redundant function?

function unnecessaryFunction(){ let details: SignInDetails = { user: user, account: account, company: company }; return details; } I am being told that the details value is unnecessary. Is there ...

Tips for correcting the `/Date(xxxxxxxxxxxxx)/` formatting issue in asp.net mvc

As a programming novice, I am trying to display data from my database server on the web using a datatable in asp.net mvc. After following a tutorial video on YouTube, I encountered an issue where the date and time columns in my table are displaying as /Dat ...

Utilizing Angular partials within specific views with the assistance of ui-router

I am currently working on developing a MEAN application and facing some challenges while handling ui-router. Within my index.html file, I have set up the template for the entire website including a header, sidebar, and content area where I have placed < ...

Why is the output showing as abnormal?

There are occasions when I am unable to successfully execute this script! var b = [9,8,7,6,5,4,3,2,1]; var a = (function(){ var W = []; for(var k in b){ W[W.length] = { index : k, fx : function(){ console.log(k); ...

The Consequences of Using Undeclared Variables in JavaScript

What is the reason behind JavaScript throwing a reference error when attempting to use an undeclared variable, but allowing it to be set to a value? For example: a = 10; //creates global variable a and sets value to 10 even though it's undeclared al ...

The console object in Chrome_browser is a powerful tool for debugging and

Having difficulty saving an amchart graph to the localstorage and retrieving the data successfully. https://i.stack.imgur.com/lJ3bJ.png In the original object, there is a mystery b, while in the new object, it appears as a normal object. In Internet Expl ...

Employ the symbol ""q" within a repetition sequence

When trying to retrieve data from a Mssql server, I encountered an issue with a function that contains a loop. The function returns some data to the callback, and now I need to figure out how to store this data from kriskowal's "q" into the resultset ...

Retrieve the id of the clicked hyperlink and then send it to JQuery

<a class = "link" href="#" id = "one"> <div class="hidden_content" id = "secret_one" style = "display: none;"> <p>This information is confidential</p> </div> <a class = "link" href="#" id = "two" style = "display: non ...

Angular 2 encountering an error with the HTTP GET request

I am currently facing some challenges with subscribing to the response while using the http method get request. Below is my service implementation: import { Injectable } from '@angular/core'; import { Http, Response } from '@angular/http&ap ...

Unable to display the complete JSON data using ng-repeat in AngularJS

Utilize ng-repeat to display data retrieved from a web service. Below is my controller JS (GetAllCtrl.js): https://i.stack.imgur.com/GAelG.jpg I have received JSON data: https://i.stack.imgur.com/0xkAU.jpg My goal now is to extract only company informati ...

Set an array to a JSON object as a fresh entity

My challenge involves working with an array that contains certain values. let myArray = [value1, value2]; I am looking to generate a JSON object in the format shown below: { "field": "[value1, value2]" } ...

The size of the array within the object does not align

I've run into a roadblock while attempting to implement the tree hierarchy in D3. Initially, I believed that I had correctly structured the JSON data, but upon inspecting the object using Developer's Tool, a discrepancy caught my eye: https://i. ...