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

时间:2022-12-04 10:16:53

I am trying to plot a line chart using chart.js with AJAX but not successful yet. The chart is plotting very fine on normal form submission and window onload event but when I use AJAX I am not able to plot it. Actually I don't know how to achieve it when the data comes from server after ajax call.

我正在尝试使用带有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;
});

In AJAX file chart.php (remote server file), I am sending the data through

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

    echo json_encode(array('labels' => $labels, 'points' => $points));

The data comes in correct format what we require in chart.js but I guess the below is the part which have something wrong:

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

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

Because in normal way on page loading after form submission, we usually draw the chart by

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

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

}

But in AJAX, i don't know how to do it after successful response from server.

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

EDIT:

After applying some solution given by some users on this website, my latest updated code in a standalone file is:

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

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));
?>

On first time page loads, the output is:

在第一次加载页面时,输出为:

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

After clicking button "Draw Chart", the output comes through AJAX is:

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

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

But when i hover my mouse over the image, it automatically converts into first image. Strange!!!

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

2 个解决方案

#1


I know this is old, but i had the same problem with my ajax implementation and i found the solution.

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

adding:

dataType: 'json'

will fix this problem. example request

将解决这个问题。示例请求

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

#2


You should use return instead of echo in your php script. Assume your php script will return right data.

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

In your html.

在你的HTML中。

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

In 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
                                        });

    }

Hope it will help!

希望它会有所帮助!

#1


I know this is old, but i had the same problem with my ajax implementation and i found the solution.

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

adding:

dataType: 'json'

will fix this problem. example request

将解决这个问题。示例请求

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

#2


You should use return instead of echo in your php script. Assume your php script will return right data.

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

In your html.

在你的HTML中。

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

In 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
                                        });

    }

Hope it will help!

希望它会有所帮助!