1

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
2
  • It looks like you're creating a new Chart() for each (key, value) pair. That can't be what you intend. Form the complete datasets array first, then create a single Chart. Commented May 13, 2020 at 15:09
  • It is sort of hard to follow. Could you please elaborate or write the code down in the answer section. Commented May 13, 2020 at 15:46

1 Answer 1

2

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
  }]
}
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks it is working, declared an array and push the values into the arrays. I am getting the desired result except the chart occupies the entire page even if I reduce the height and width of canvas. Any specific reason why I am unable to resize the canvas/chart?
@nomadev95 There is a section in the docs that addresses responsive charts that adjust to the window size: chartjs.org/docs/latest/general/responsive.html
I have added options: {responsive: true, maintainAspectRatio: false} and have set size inside canvas tag. Still no luck though

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.