nomadev95
nomadev95

Reputation: 125

How do I display chart on my HTML page based on JSON data sent by Node JS

I wish to display my JSON data on client side HTML/JS which is fetched from server side NodeJS API in the form of a chart using chartjs or D3.js (or anything which seems relevant).

Here is my index.html

<script
  src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.min.js"></script>
<canvas id="chart" height="400px" width="400px"></canvas>
<script type="text/javascript">
  $(document).ready(function () {
    $.ajax({
      url: 'http://localhost:8050/api/opcounterTest',
      type: 'POST',
      dataType: 'json',
      success: function (res) {
        console.log(res);
        divData = '';
        var myLabels = [];
        var myData = [];
        $.each(res, function (key, value) {
          console.log(key);
          console.log(value);
          myLabels.push(key);
          myData.push(value);
        });

        var ctx = document.getElementById('chart');

        var myBarChart = new Chart(ctx, {
          type: 'pie',
          data: {
            labels: myLabels,
            datasets: [{
              label: 'Labels',
              data: myData,

              backgroundColor: [
                'rgba(75, 192, 192, 0.2)',
                'rgba(255, 99, 132, 0.2)'
              ],
              borderColor: [
                'rgba(75, 192, 192, 1)',
                'rgba(255,99,132,1)'
              ],
              borderWidth: 1
            }]
          },
          options: {
            responsive: true,
            maintainAspectRatio: false
          }
        });

      }
    });
  });
</script>

This is what I came up with having very minimum knowledge of charts. For time being I plan on plotting the data on a pie chart.

Console Log Result

{insert: 0, query: 524, update: 0, delete: 0, getmore: 22492, …}
command: 169411
delete: 0
getmore: 22492
insert: 0
query: 524
update: 0
__proto__: Object

Upvotes: 1

Views: 779

Answers (1)

terrymorse
terrymorse

Reputation: 7086

You are creating a new Chart() every time through your $.each() loop.

Your logic goes like this:

for each (key, value) in res:
  create a new Chart containing just this (key, value)

You almost certainly want this:

create empty arrays myLabels[] and myData[]

for each (key, value) in res:
  add key to myLabels[]
  add value to myData[]

then
  create one (and only one) new Chart using myLabels[] and myData[]

Your data property for new Chart() will then look like this:

data: {
  labels: myLabels,
  datasets: [{
    label: 'Labels',
    data: myData,

    backgroundColor: [
      'rgba(75, 192, 192, 0.2)',
      'rgba(255, 99, 132, 0.2)'
    ],

    borderColor: [
      'rgba(75, 192, 192, 1)',
      'rgba(255,99,132,1)'
    ],
    borderWidth: 1
  }]
}

Upvotes: 2

Related Questions