如何使用带有ajax的chart.js绘制折线图?

时间:2015-05-04 06:56:05

标签: javascript php jquery ajax

我正在尝试使用带有AJAX的chart.js绘制折线图但尚未成功。该图表在正常表单提交和窗口载入事件上绘制得很好,但是当我使用AJAX时,我无法绘制它。实际上,当ajax调用后数据来自服务器时,我不知道如何实现它。

HTML:

<form method="post" action="" id="order_form">
<label for="selogtype">Graph Type:</label>
<select name="selogtype" id="selogtype">
<option value="total_order_value">Total Order Value</option>
<option value="total_order_qty">Total Order Quantity</option>
<option value="avg_order_value">Average Order Value</option>
<option value="avg_order_qty">Average Order Quantity</option>
</select>
<br /><br />
<label for="radodays">Duration:</label>
<input type="radio" name="radoduration" id="radodays" value="days" checked='checked' /><label for="radodays">Days</label>
<input type="radio" name="radoduration" id="radodates" value="dates" /><label for="radodates">Date Range</label>
<div id="div_odays">
<select name="seloduration">
<option value="week">Last 7 Days</option>
<option value="month">Last 30 Days</option>
<option value="curweek">Current Week</option>
<option value="curmonth">Current Month</option>
</select>
</div>
<div id="div_odate">
<span class="spanodate">Start Date:</span> <input type="text" name="txtosdate" id="txtosdate" value="" />&nbsp;&nbsp;&nbsp;
<span class="spanodate">End Date:</span> <input type="text" name="txtoedate" id="txtoedate" value="" />
</div>
<input type="submit" name="btnorderchart" id="btnorderchart" value="Draw Chart" />
</form>
<div id="outer_ocanvas" style="margin-top:25px;">
<canvas id="ocanvas" height="400" width="800"></canvas>
</div>

JS:

// ajax part of chart //
// order //
$("#order_form").submit(function(){
var btnorderchart = $("#btnorderchart").attr("name") + "=" + $("#btnorderchart").val();
    $.ajax({
        beforeSend: function(){ sendRequest("outer_ocanvas"); },
        cache: false,
        type: "POST",
        dataType: "json",
        url: "ajax/chart.php",
        data: $(this).serialize() + "&" + btnorderchart,
        success: function(data){
            //alert(data.labels);
            //alert(data.points);

        var lineChartData = {
            labels : "[" +  data.labels + "]",
            datasets : [
                {
                    label: "Recent Orders",
                    fillColor : "rgba(150,150,245,0.2)",
                    strokeColor : "rgba(0,0,255,1)",
                    pointColor : "rgba(220,220,220,1)",
                    pointStrokeColor : "#fff",
                    pointHighlightFill : "#fff",
                    pointHighlightStroke : "rgba(220,220,220,1)",
                    data : "[" +  data.points + "]",
                }
            ]

        }

        var ctx = document.getElementById("ocanvas").getContext("2d");
        window.myLine = new Chart(ctx).Line(lineChartData, {
            responsive: false
        });
        },
    });
return false;
});

在AJAX文件chart.php(远程服务器文件)中,我通过

发送数据
    echo json_encode(array('labels' => $labels, 'points' => $points));

我们在chart.js中要求的数据格式正确,但我猜以下是有错误的部分:

        var ctx = document.getElementById("ocanvas").getContext("2d");
        window.myLine = new Chart(ctx).Line(lineChartData, {
            responsive: false
        });
        },

因为在表单提交后以正常方式页面加载,我们通常按

绘制图表
window.onload = function(){
        var ctx = document.getElementById("ocanvas").getContext("2d");
        window.myLine = new Chart(ctx).Line(lineChartData, {
            responsive: false
        });

}

但是在AJAX中,我不知道在服务器成功响应之后该怎么做。

修改

在本网站上应用某些用户提供的解决方案后,我在独立文件中的最新更新代码为:

的index.html:

<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>AJAX JSON Chart</title>
<script type="text/javascript" src="js/jquery-1.11.0.min.js"></script>
<script type="text/javascript" src="js/Chart.min.js"></script>
<script type="text/javascript">
var randomScalingFactor = function(){ return Math.round(Math.random()*100)};
var lineChartData = {
    labels : ["January","February","March","April","May","June","July"],
    datasets : [
        {
            label: "My First dataset",
            fillColor : "rgba(220,220,220,0.2)",
            strokeColor : "rgba(220,220,220,1)",
            pointColor : "rgba(220,220,220,1)",
            pointStrokeColor : "#fff",
            pointHighlightFill : "#fff",
            pointHighlightStroke : "rgba(220,220,220,1)",
            data : [randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor()]
        }
    ]

}

window.onload = function(){
var ctx = document.getElementById("canvas").getContext("2d");
window.myLine = new Chart(ctx).Line(lineChartData, {
    responsive: false
});
}

// ajax part of chart //
$(document).ready(function(e) {
    $("#frm1").submit(function(){
var canvas = document.getElementById('canvas');
   ctx = canvas.getContext('2d');

 //  ctx = $('#canvas').get(0).getContext("2d");

    var btnchart = $("#btnchart").attr("name") + "=" + $("#btnchart").val();
        $.ajax({
            //beforeSend: function(){ sendRequest("canvas"); },
            cache: false,
            type: "POST",
            dataType: "json",
            url: "ajax/chart.php",
            data: $(this).serialize() + "&" + btnchart,
            success: function(data){
                //alert(data.labels);
                //alert(data.points);
                renderGraph(data.labels, data.points, ctx);
            },
        });
    return false;
    });
});

var renderGraph = function (labels, points, ctx) {
       // var ctx = $("#canvas")[0].getContext("2d");

        var lineChartData = {
                        labels: "[" +  labels + "]",
                        datasets: [
                            {
                                label: "Recent Orders",
                                fillColor: "rgba(220,220,220,0.2)",
                                strokeColor: "rgba(220,220,220,1)",
                                pointColor: "rgba(220,220,220,1)",
                                pointStrokeColor: "#fff",
                                pointHighlightFill: "#fff",
                                pointHighlightStroke: "rgba(220,220,220,1)",
                                data: "[" +  points + "]", 
                            }
                        ]
                    };


        var myChart = new Chart(ctx)
                                .Line(lineChartData, {
                                        responsive: false,
                                        animation: false
                                        });
                                        //myChart.update(lineChartData);

    }

function sendRequest(id)
{
    $("#"+id).html('<div style="width:100px; margin:0 auto;"><img id="loader-img" alt="" src="images/preloader.gif" width="100" height="100" /></div>');
}


</script>
</head>
<body>
<div style="width:30%">
    <div>
        <canvas id="canvas" height="450" width="960"></canvas>
    </div>
</div>
<form id="frm1" name="frm1" method="post" action="">
<input type="submit" name="btnchart" id="btnchart" value="Draw Chart" />
</form>
</body>
</html>

chart.php:

<?php
$labels = array('29 April 2015', '30 April 2015', '1 May 2015', '2 May 2015', '3 May 2015', '4 May 2015', '5 May 2015');
$points = array('100', '250', '10', '35', '73', '0', '25');
echo json_encode(array('labels' => $labels, 'points' => $points));
?>

首次加载页面时,输出为:

enter image description here

单击“绘制图表”按钮后,通过AJAX输出的是:

enter image description here

但是当我将鼠标悬停在图像上时,它会自动转换为第一张图像。奇怪!!!

2 个答案:

答案 0 :(得分:1)

我知道这是旧的,但我的ajax实现遇到了同样的问题,我找到了解决方案。

中加入:

dataType: 'json'

将解决此问题。 示例请求

$.ajax({url: "chartData.php",
    async: false,
    dataType: 'json',
    success: function(result){
        //...
}});

答案 1 :(得分:0)

你应该在php脚本中使用return而不是echo。 假设您的php脚本将返回正确的数据。

在你的HTML中。

<canvas id="request" width="450" height="200"></canvas>

在jquery中,

$(document).ready(function(){
    $.ajax({
               type: "POST",
                dataType: "json",
                url: "ajax/chart.php",
                data: //data to send,
                beforeSend: function(){ 
                    // Do staff before send
                },
                success: function(data){
                    renderGraph(data.labels, data.points);
                }
            });
});

var renderGraph = function (labels, points) {

        var canvas = $("#request")[0].getContext("2d");

        var data = {
                        labels: labels,
                        datasets: [
                            {
                                label: "Recent Orders",
                                fillColor: "rgba(220,220,220,0.2)",
                                strokeColor: "rgba(220,220,220,1)",
                                pointColor: "rgba(220,220,220,1)",
                                pointStrokeColor: "#fff",
                                pointHighlightFill: "#fff",
                                pointHighlightStroke: "rgba(220,220,220,1)",
                                data: points 
                            }
                        ]
                    };

        var myChart = new Chart(canvas)
                                .Line(data, {
                                        responsive: true,
                                        animation: true
                                        });

    }

希望它会有所帮助!