简体   繁体   中英

A pie chart in chart.js with data from json

I'm drawing a pie chart using data from a database. My database is very simple, but it has a different structure than all examples which I was checking. So it looks like this:

id | food | tickets
1  | 300  | 50 

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

data.php

 <?php
//setting header to json
header('Content-Type: application/json');

require_once "../polaczenie.php";

//get connection
$mysqli = @new mysqli($host,$db_user,$db_password,$db_name);

if(!$mysqli){
    die("Connection failed: " . $mysqli->error);
}

//query to get data from the table
$query = sprintf("SELECT id,food, tickets FROM arch_kategorie ORDER BY id");

//execute query
$result = $mysqli->query($query);

//loop through the returned data
$data = array();
foreach ($result as $row) {
    $data[] = $row;
}

//free memory associated with result
$result->close();

//close connection
$mysqli->close();

//now print the data
print json_encode($data);
?>

When I'm checking results by localhost://data.php I have this: [{"food":"300","tickets":"50"}]

And now the problematic part:

app.php

$(document).ready(function(){
    $.ajax({
        url : "data.php",
        type : "GET",
        success : function(data){
            console.log(data);

            var food= [];
            var tickets= [];

            for(var i in data) {
                food.push(data[i].food);
                tickets.push(data[i].tickets);
            }

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

            var data = {
                labels : ["food", "tickets"],
                datasets : [{
                    label : "Result",
                    data : food, 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 : data,
                options : options
            });
        });
    },
    error : function(data) {
        console.log(data);
    }
});

And of course html:

index.html

<style type="text/css">
    #chart-container {
        width: 80%;
        height: auto;
    }
</style>

<div class="chart-container">
    <div class="chart-container">
        <canvas id="chartcanvas-1"></canvas>
    </div>
</div>

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 dataset s 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, ie using a for loop. So it depends on you 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 (ie 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:

function plot(data) {
  console.log(data);

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

  var datasets = data.map(row => {
    let sets = {
      label: row.id,
      data: [Number(row.food), Number(row.tickets)],
      backgroundColor: [
        "#DEB887",
        "#A9A9A9"
      ],
      borderColor: [
        "#CDA776",
        "#989898"
      ],
      borderWidth: [1, 1]
    };
    return sets;
  });
  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
  });
  
}

Finally: Emily, if you received and read this, please contact me on Skype...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM