ChartJS和JSON结果:无法设置未定义的属性'fillColor'

时间:2016-03-16 12:46:23

标签: php jquery ajax chart.js

修改

我只是看到了这个:

enter image description here

编辑结束

我有这个PHP代码从MySQL中选择多行,结果将使用json_encode进行编码,因此我们可以在AJAX脚本中获取它并在ChartJS的条形图中设置数组的结果。

<?php
//Set error reporting on
error_reporting(E_ALL);
ini_set("display_errors", 1);

//Include connection file
require_once('../include/global.php');

//Json and PHP header
header('Content-Type: application/json');
$arr = array();
$user = $_SESSION['username'];
$id_logged = $_SESSION['login_id'];



$date1 = $_POST['current_year'];

    $res = array();
    $c = "cash";
    $i = "installment";
    //SUM of cash paid Month
    $sql = "SELECT 
    sum(cost) as cost

FROM 
(
    SELECT 
        sum(project_cost) as cost, 
        month(date_now) as month 
    FROM 
        dentist.patient_info 
    WHERE id_logged=:logged AND year(date_now)=:year_now AND payment_type=:pt 
    GROUP BY month(date_now)

    UNION SELECT 0,1
    UNION SELECT 0,2
    UNION SELECT 0,3
    UNION SELECT 0,4
) tmp
GROUP BY month";
$sqlStmt = $conn->prepare($sql);
$sqlStmt->bindValue(":logged", $id_logged);
$sqlStmt->bindValue(":pt", $c);
$sqlStmt->bindValue(":year_now", $date1);
$exec = $sqlStmt->execute();
$res = $sqlStmt->fetchAll();

echo json_encode($res);

?>

这是我的AJAX脚本:

$(document).ready(function() {
  //Get the current year and display it in year text box
  var d = new Date();
  y = d.getFullYear();
  res = $("#id_year").val(y);
  $.ajax
  ({
    url: 'stat_income.php',
    type: 'POST',
    data: {current_year: y},
    dataType: 'JSON',
    success:function(res)
    {
      $.each(res, function( key, row)
      {
        console.log(row['cost']);
        var areaChartData = {
          labels: ["January", "February", "March", "April", "May", "June", "July", "August"
          , "September", "October", "November", "December"],
          datasets: [
            {
              label: "Electronics",
              strokeColor: "rgba(210, 214, 222, 1)",
              pointColor: "rgba(210, 214, 222, 1)",
              pointStrokeColor: "#c1c7d1",
              pointHighlightFill: "#fff",
              pointHighlightStroke: "rgba(220,220,220,1)",
              data: row['cost']
            }
          ]
        };
  var barChartCanvas = $("#barChart").get(0).getContext("2d");
        var barChart = new Chart(barChartCanvas);
        var barChartData = areaChartData;
        barChartData.datasets[0].fillColor = "#00a65a";
        barChartData.datasets[0].strokeColor = "#00a65a";
        barChartData.datasets[0].pointColor = "#00a65a";
        var barChartOptions = {
          //Boolean - Whether the scale should start at zero, or an order of magnitude down from the lowest value
          scaleBeginAtZero: true,
          //Boolean - Whether grid lines are shown across the chart
          scaleShowGridLines: true,
          //String - Colour of the grid lines
          scaleGridLineColor: "rgba(0,0,0,.05)",
          //Number - Width of the grid lines
          scaleGridLineWidth: 1,
          //Boolean - Whether to show horizontal lines (except X axis)
          scaleShowHorizontalLines: true,
          //Boolean - Whether to show vertical lines (except Y axis)
          scaleShowVerticalLines: true,
          //Boolean - If there is a stroke on each bar
          barShowStroke: true,
          //Number - Pixel width of the bar stroke
          barStrokeWidth: 2,
          //Number - Spacing between each of the X value sets
          barValueSpacing: 5,
          //Number - Spacing between data sets within X values
          barDatasetSpacing: 1,
          //String - A legend template
          legendTemplate: "<ul class=\"<%=name.toLowerCase()%>-legend\"><% for (var i=0; i<datasets.length; i++){%><li><span style=\"background-color:<%=datasets[i].fillColor%>\"></span><%if(datasets[i].label){%><%=datasets[i].label%><%}%></li><%}%></ul>",
          //Boolean - whether to make the chart responsive
          responsive: true,
          maintainAspectRatio: true
        };

        barChartOptions.datasetFill = false;
        barChart.Bar(barChartData, barChartOptions);
      });
    },
    error:function(res)
    {
      console.log(res);
    }
  });
});

我收到以下错误:

  

stat.php:111 Uncaught TypeError:无法设置属性'fillColor'   未定义

这是我的网络XHR结果:

enter image description here

我试图设定一个条件:

    if(row['cost']==undefined)
    {
      row['cost']=0;
    }

但仍然得到同样的错误。

1 个答案:

答案 0 :(得分:2)

快速查看后,我在datasets变量的areaChartData数组中只看到1个元素。

 var areaChartData = {
      labels: ["January", "February", "March", "April", "May", "June", "July", "August"
      , "September", "October", "November", "December"],
      datasets: [
        {
          label: "Electronics",
          strokeColor: "rgba(210, 214, 222, 1)",
          pointColor: "rgba(210, 214, 222, 1)",
          pointStrokeColor: "#c1c7d1",
          pointHighlightFill: "#fff",
          pointHighlightStroke: "rgba(220,220,220,1)",
          data: row['cost']
        }
      ]
    };

在这里,您尝试访问datasets[1]

var barChartData = areaChartData;
barChartData.datasets[1].fillColor = "#00a65a";
barChartData.datasets[1].strokeColor = "#00a65a";
barChartData.datasets[1].pointColor = "#00a65a";

我不确定我100%理解您尝试编码的内容,但如果您想修改数据集的颜色,则应定位barChartData.datasets[0]

如果您的目标是插入第二个数据集,则必须先插入一个对象:

barChartData.datasets.push({ }); // A new object for a second dataset to modify at barChartData.datasets[1]
barChartData.datasets[1].fillColor = "#00a65a";
barChartData.datasets[1].strokeColor = "#00a65a";
barChartData.datasets[1].pointColor = "#00a65a";
// Don't forget to set also the label and the data

修改:对于问题的继续: 仅使用循环从检索到的JSON中提取所需的数据,不要多次实例化图表。尝试一下:(未经测试)

$(document).ready(function() {
//Get the current year and display it in year text box
var d = new Date();
y = d.getFullYear();
res = $("#id_year").val(y);
$.ajax
({
  url: 'stat_income.php',
  type: 'POST',
  data: {current_year: y},
  dataType: 'JSON',
  success:function(res)
{

  var costData = []; // In this array we will format data from the retrieve JSON array

  $.each(res, function( key, row)
  {
    costData.push(row['cost']);
  });

  var areaChartData = {
      labels: ["January", "February", "March", "April", "May", "June", "July", "August"
      , "September", "October", "November", "December"],
      datasets: [
        {
          label: "Electronics",
          strokeColor: "rgba(210, 214, 222, 1)",
          pointColor: "rgba(210, 214, 222, 1)",
          pointStrokeColor: "#c1c7d1",
          pointHighlightFill: "#fff",
          pointHighlightStroke: "rgba(220,220,220,1)",
          data: costData
        }
      ]
  };

  var barChartCanvas = $("#barChart").get(0).getContext("2d");
    var barChart = new Chart(barChartCanvas);
    var barChartOptions = {
      //Boolean - Whether the scale should start at zero, or an order of magnitude down from the lowest value
      scaleBeginAtZero: true,
      //Boolean - Whether grid lines are shown across the chart
      scaleShowGridLines: true,
      //String - Colour of the grid lines
      scaleGridLineColor: "rgba(0,0,0,.05)",
      //Number - Width of the grid lines
      scaleGridLineWidth: 1,
      //Boolean - Whether to show horizontal lines (except X axis)
      scaleShowHorizontalLines: true,
      //Boolean - Whether to show vertical lines (except Y axis)
      scaleShowVerticalLines: true,
      //Boolean - If there is a stroke on each bar
      barShowStroke: true,
      //Number - Pixel width of the bar stroke
      barStrokeWidth: 2,
      //Number - Spacing between each of the X value sets
      barValueSpacing: 5,
      //Number - Spacing between data sets within X values
      barDatasetSpacing: 1,
      //String - A legend template
      legendTemplate: "<ul class=\"<%=name.toLowerCase()%>-legend\"><% for (var i=0; i<datasets.length; i++){%><li><span style=\"background-color:<%=datasets[i].fillColor%>\"></span><%if(datasets[i].label){%><%=datasets[i].label%><%}%></li><%}%></ul>",
      //Boolean - whether to make the chart responsive
      responsive: true,
      maintainAspectRatio: true,
      datasetFill: false
    };

    barChart.Bar(areaChartData, barChartOptions);
},
error:function(res)
{
  console.log(res);
}
});
});

说明:目标是为数据集传递一个整数数组([0, 0, 1100, 0, 0, 0, 0, 0, 0, 0, 0, 0]