Chartjs-How to implement dynamic data on chartjs?

1๐Ÿ‘

I have used $.ajax() to fetch JSON data, and save the data in two arrays, then you can use these arrays for your chart label and data. Hope this helps!

 var lbl = [];
    var dta = [];

    $.ajax({
      url: "test.json",
      dataType: 'json',
      async: false,
      success: function(data) {
        $.each(data, function(i, field){
             lbl.push(field.EFICAZ_TAB_ITEM_ID
    );
               dta.push(field.EFICAZ_PERCENTS);

           });
      }
    });


     $.getJSON("test.json", function(result){
           $.each(result, function(i, field){
             lbl.push(field.EFICAZ_TAB_ITEM_ID
    );
               dta.push(field.EFICAZ_PERCENTS);

           });
        });


    var ctx = document.getElementById("myCanvas").getContext('2d');



    var chart = new Chart(ctx, {
        // The type of chart we want to create
        type: 'line',

        // The data for our dataset
        data: {
            labels: lbl,
            datasets: [{
                label: "My First dataset",
                backgroundColor: 'rgb(255, 99, 132)',
                borderColor: 'rgb(255, 99, 132)',
                data: dta,
            }]
        },

        // Configuration options go here
        options: {}
    });

1๐Ÿ‘

Here is example

document.addEventListener('DOMContentLoaded', function(){
  
  var chartData = [
   {
      "EFICAZ_TAB_ITEM_ID":1,
      "EFICAZ_PERCENTS":21
   },
   {
      "EFICAZ_TAB_ITEM_ID":2,
      "EFICAZ_PERCENTS":55
   },
   {
      "EFICAZ_TAB_ITEM_ID":3,
      "EFICAZ_PERCENTS":32
   }
]
 
 var labels = [];
 var values = [];
 chartData.forEach(function(el,key){
  labels.push(el.EFICAZ_TAB_ITEM_ID);
  values.push(el.EFICAZ_PERCENTS);
})
var ctx = document.getElementById('myChart').getContext('2d');
var chart = new Chart(ctx, {
    // The type of chart we want to create
    type: 'line',

    // The data for our dataset
    data: {
        labels: labels,
        datasets: [{
            label: "My First dataset",
            backgroundColor: 'rgb(255, 99, 132)',
            borderColor: 'rgb(255, 99, 132)',
            data: values,
        }]
    },

    // Configuration options go here
    options: {}
});
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.min.js"></script>
<canvas id="myChart" width="400" height="200"></canvas>

Leave a comment