Chartjs-Chartjs and dynamic data arrays

1đź‘Ť

âś…

issue one: global scope:

This is +- your code outline (You run function each time and only changed the original person var new object pointer –> This is why your code only creates only one “person” (or chart).

var person;

function hello(){
  person = new Object();
  person.firstName = 'testFirstName';
  person.lastName = 'testLastName';
}

hello();

function hello2(){
  person = new Object();
  person.firstName = 'test_2_FirstName';
  person.lastName = 'test_2_LastName';
}

hello2();

console.log(person.firstName); /*return test_2_FirstName */

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var

Issue two: More than one dataset = array of datasets

Very hard to understand exactly your issue (Please add a minimal reproducible-example).
https://stackoverflow.com/help/minimal-reproducible-example

Anyway, this is hello world most basic example (Add one dataset on click and hide button).

var data = {
  labels: ["Africa", "Asia", "Europe", "America"],
  datasets: [
    {
      /* data */
      label: "Dataset1 (millions)",
      backgroundColor: ["#490A3D", "#BD1550","#E97F02", '#F8CA00'],
      data: [1000,1500,2000, 2200]
    }
  ]
};

var options = {
  scales: {
    xAxes: [{
      stacked: false
    }],
    yAxes: [{
      stacked: false
    }]
  }
};

var myChart = new Chart(document.getElementById("chart"), {
  type: 'bar',
  data: data,
  options: options
});

var add_this_dataset_on_click = {
  /* data */
  label: "Dataset2 (millions)",
  backgroundColor: ["purple", "magenta","orange", 'yellow'],
  data: [500,750,1000, 1100]
}

function addData() {
  myChart.data.datasets.push(add_this_dataset_on_click);
  myChart.update();
  document.getElementById("btn").style.display = "none";
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<button id="btn" onclick="addData()">Add dataset</button>

<canvas id="chart"></canvas>

My advice. Start with “hello world” example (Without PHP and dynamic data).

Leave a comment