Jump to content


Check out our Community Blogs

Register and join over 40,000 other developers!


Recent Status Updates

View All Updates

Photo
- - - - -

Updating chart.js in ajax doesn't render the graph properly

php ajax jquery

This topic has been archived. This means that you cannot reply to this topic.
No replies to this topic

#1 sachinsharma1507

sachinsharma1507

    CC Resident

  • Advanced Member
  • PipPipPipPip
  • 57 posts

Posted 03 June 2015 - 12:25 AM

I am trying to plot a line chart using chart.js with AJAX but the chart is not plotted properly when data comes from server. The chart is plotting fine on window onload event but with AJAX it failed to render properly. What could be the issue? Here is my code -

 

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

    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 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:

 

D8bBr.png

 

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

 

 

oN1EN.png

 

But when i hover my mouse over the image, it automatically converts into first image i.e. the first correct graph when window was loaded. Strange!!!






Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download