[Chartjs]-A pie chart in chart.js with data from json

0👍

First of all you have a second definition of variable data in your Ajax success function. Function arguments (parameters) work as local variables inside functions, that is the same way as they were defined with the keyword let inside the function.

Second, data in datasets require to be a number[] and your values that you get in JSON are strings.

Third, one thing is unclear to me, since describing your data set you wrote that:

I guess the id column is unnecessary because it won’t be more records.

but then you process the data inside of the Ajax success function as it was a multi element array of objects, i.e. using a for loop.
So it depends on you’d want to achieve with what type of data.
A trivial solution with a single row from your SQL table the Ajax success function would look like:

success: function(data) {
  console.log(data);

  var ctx1 = $("#chartcanvas-1");
  
  var chartData = {
    labels : ["food", "tickets"],
    datasets : [{
      label : "Result",
      data : [Number(data[0].food), Number(data[0].tickets)],
      backgroundColor : [
        "#DEB887",
        "#A9A9A9"
      ],
      borderColor : [
        "#CDA776",
        "#989898"
      ],
      borderWidth : [1, 1]
    }]
  };
  
  var options = {
    title : {
      display : true,
      position : "top",
      text : "Pie Chart",
      fontSize : 18,
      fontColor : "#111"
    },
    legend : {
      display : true,
      position : "bottom"
    }
  };
  
  var chart1 = new Chart(ctx1, {
    type : "pie",
    data : chartData,
    options : options
  });
}

With multiple rows taken from your SQL table you could use each array object (i.e. your SQL row including the id field used as a label) as a separate dataset. Since the datasets is a JSON array of objects you could transform your initial data as follows:

success: function(data) {
  console.log(data);

  var ctx1 = $("#chartcanvas-1");

  var datasets = data.map(row => {
    let set = {
      label: row.id,
      data: [Number(row.food), Number(row.tickets)],
      backgroundColor: [
        "#DEB887",
        "#A9A9A9"
      ],
      borderColor: [
        "#CDA776",
        "#989898"
      ],
      borderWidth: [1, 1]
    };
    return set;
  });
  console.log(datasets);
  
  var chartData = {
    labels : ["food", "tickets"],
    datasets : datasets
  };
  
  var options = {
    title : {
      display : true,
      position : "top",
      text : "Pie Chart",
      fontSize : 18,
      fontColor : "#111"
    },
    legend : {
      display : true,
      position : "bottom"
    }
  };
  
  var chart1 = new Chart(ctx1, {
    type : "pie",
    data : chartData,
    options : options
  });
}

Leave a comment