drui0508
2016-08-07 16:15
浏览 86
已采纳

如何使用sql数据填充chart.js?

I'm using chart.js to generate charts on my page. However I want these charts to be populated by my SQL database. I'm able to get my data out of my database, but I won't draw the chart

I got a canvas on my main page called "OmzetChart" , this is where the chart should come.

<script>
    $.ajax({
        type: 'POST',
        url: 'templates/getdata.php',
        success: function (data) {
            lineChartData = data;
            //alert(JSON.stringify(data));

            var ctx = document.getElementById("OmzetChart").getContext("2d");
            var myLineChart = new Chart(ctx, {
                type: 'line',
                data: lineChartData

            });
       }
    });

</script>

The page of GetData.php results in the following (This is what I need, just want it into my chart):

[{"dag":"23","0":"23","uur":"13","1":"13","SomOmzet":"23.00","2":"23.00"},{"dag":"23","0":"23","uur":"18","1":"18","SomOmzet":"2.50","2":"2.50"}]

Getdata.php: 
<?php
include ("../PDO.php");


$conn = DatabasePDO::getInstance();
$sql = "SELECT DATEPART(DD, receiptdatetime) as dag ,DATEPART(hh, receiptdatetime) as uur, ISNULL(abs(cast(sum(NetAmount) as decimal (10,2))),0) as SomOmzet FROM ReceiptLine a , Receipt b, ReceiptLineDetail c 
where a.LineType = 200 and a.receiptID = b.receiptid and a.receiptlineID = c.receiptlineID
group by DATEPART(DD, receiptdatetime), DATEPART(hh, receiptdatetime)";
$st = $conn->prepare($sql);
$st->execute();
$list = array();

while ( $row = $st->fetch() ) {
    $list[] = $row;

}
$conn = null;

echo json_encode( $list );

?>
  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • douzhanjia0773 2016-08-07 21:15
    已采纳

    json_encode() produces a JSON string. You need to parse this with JSON.parse() before you can use it.

    $.ajax({
        type: 'POST',
        url: 'templates/getdata.php',
        success: function (data) {
            lineChartData = JSON.parse(data); //parse the data into JSON
    
            var ctx = document.getElementById("OmzetChart").getContext("2d");
            var myLineChart = new Chart(ctx, {
                type: 'line',
                data: lineChartData
            });
        }
    });
    

    Also, using $.ajax() method's dataType parameter, you can leave this parsing to jQuery.

    $.ajax({
        type: 'POST',
        url: 'templates/getdata.php',
        dataType: 'json', //tell jQuery to parse received data as JSON before passing it onto successCallback
        success: function (data) {
            var ctx = document.getElementById("OmzetChart").getContext("2d");
            var myLineChart = new Chart(ctx, {
                type: 'line',
                data: data //jQuery will parse this since dataType is set to json
            });
        }
    });
    
    已采纳该答案
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题