[Chartjs]-How to create datasets dynamically for chart.js Line chart?

14👍

I think you are looking for something like the following solution.
http://jsfiddle.net/5m63232a/

var datasetValue = [];
var count = 10;
for (var j=0; j<count; j++) {
    datasetValue[j] = {
        fillColor: 'rgba(220,220,220,0.5)',
        strokeColor :'rgba(220,220,220,1)',
        title :'2013',
        data : [Math.round(Math.random() * 100),Math.round(Math.random() * 100)-10]
    }
}
var mydata = {
    datasets : datasetValue
}
alert("Datasets: "+mydata.datasets[0].data);

6👍

Create service to fetch json formt like :

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()]
            },
            {
                label: "My Second dataset",
                fillColor : "rgba(151,187,205,0.2)",
                strokeColor : "rgba(151,187,205,1)",
                pointColor : "rgba(151,187,205,1)",
                pointStrokeColor : "#fff",
                pointHighlightFill : "#fff",
                pointHighlightStroke : "rgba(151,187,205,1)",
                data : [randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor()]
            }
        ]  

Then add following javascript code

var j = [];
$.ajax({
    type: 'GET',
    url: 'http://' + window.location.host.toString() + "/path",
    dataType: 'json',
    success: function (data) {
       j = data;
    },
    async: false
 });
 var chartData = {
     labels: j.labels,
     datasets: j.datasets
 };
 window.onload = function () {
     var ctx = document.getElementById("canvas").getContext("2d");
     window.myLine = new Chart(ctx).Line(chartData, {
         responsive: true,
         animation: true,
         tooltipFillColor: "rgba(0,0,0,0.8)",
         multiTooltipTemplate: "<%= datasetLabel %> - <%=value %>"
     });
 }

Leave a comment