Thursday, January 30, 2020

How to integrate Chart.js to load Dynamic JSON from fetched API

HTML code:

 <div class="row">
                            <div class="col-lg-12">
                                <div class="au-card m-b-30">
                                    <div class="au-card-inner">
                                        <h3>Last 10 Days Payments Chart</h3>
                                        <canvas id="singelBarChart"></canvas>
                                    </div>
                                </div>
                            </div>
 </div>

Javascript code: 


try {
    // single bar chart
    var ctx = document.getElementById("singelBarChart");
    if (ctx) {
    fetch('http://localhost:8081/wmsadmin/lastPayments')
    .then(response => {
      return response.json()
    })
    .then(myData => {
      // Work with JSON data here
    var chartdatat = myData;
      console.log(chartdatat)
   
      ctx.height = 150;
      var myChart = new Chart(ctx, {
        type: 'bar',
        data: {
          labels: ["Today", "Yesterday", "3", "4", "5", "6", "7", "8", "9", "10"],
          datasets: [
            {
              label: "Payment",
              data: chartdatat,
              borderColor: "rgba(0, 123, 255, 0.9)",
              borderWidth: "0",
              backgroundColor: "rgba(0, 123, 255, 0.5)"
            }
          ]
        },
        options: {
          legend: {
            position: 'top',
            labels: {
              fontFamily: 'Poppins'
            }

          },
          scales: {
            xAxes: [{
              ticks: {
                fontFamily: "Poppins"

              }
            }],
            yAxes: [{
              ticks: {
                beginAtZero: true,
                fontFamily: "Poppins"
              }
            }]
          }
        }
      });
  })
    }

  } catch (error) {
    console.log(error);
  }

})(jQuery);

Result:

No comments:

Post a Comment