Kim Carlo
Kim Carlo

Reputation: 1223

Chart JS not displaying graph

I am working with Chart JS and the graph data wont show up. I'm pretty sure I followed the proper way of implementing it but the graph data doesn't show up..

This is the data response from the API.

response: {
   "users": {
      "1": 3,
      "2": 0,
      "3": 0,
      "4": 0,
      "5": 0,
      "6": 0,
      "7": 0,
      "8": 0,
      "9": 0,
      "10": 0,
      "11": 0,
      "12": 0
   },
   "males": 3,
   "females": 0,
   "docs": {
      "1": 3,
      "2": 0,
      "3": 0,
      "4": 0,
      "5": 0,
      "6": 0,
      "7": 0,
      "8": 0,
      "9": 0,
      "10": 0,
      "11": 0,
      "12": 0
     },
   "regular": 3,
   "contractual": 0
}

and here's how I implement the charts

 var userData;
        var genderData;
        var docsData;
        var empStatusData;

        $.ajax({
            url : dataUrl,
            type : 'GET',
            success : function(response){

                userData = response.users;
                genderData = [response.males,response.females];
                docsData = response.docs;
                empStatusData = [response.regular,response.contractual];
            }
        })
        let chart = document.getElementById('users-chart').getContext('2d');
        let popChart = new Chart(chart,{
            type  : 'bar',
            data : {
                labels : ['Jan', 'Feb', 'Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'],
                datasets : [{
                     label: 'User Registrations this year',
                     data: userData,
                     backgroundColor: 'rgba(0, 119, 204, 0.3)'
                }]
            }

        });

I only get a blank graph with no data in it. what am I doing wrong here?

Appreciate the help. Thanks everyone.

Upvotes: 0

Views: 572

Answers (1)

Mika Sundland
Mika Sundland

Reputation: 18979

It's not as easy as that. To update the chart you have to access the chart variable and then update its fields. You then call the update() function of the chart. Like this:

$.ajax({
  url: dataUrl,
  type: 'GET',
  success: function (response) {
    popChart.data.datasets[0].data = response.users;
    popChart.update();
  }
});

You can also create functions that do this to make the code more readable. Like in the official documentation.

You have one more problem with your code. In the response you are getting users and docs as objects with several fields representing months. Chart.js wants the data as an array:

"users": [3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

rather than

"users": { "1": 3, "2": 0, "3": 0, "4": 0, "5": 0, "6": 0, "7": 0, "8": 0, "9": 0, "10": 0, "11": 0, "12": 0 }

If you can change the server-side code you should do it there. If not you can convert the users/docs response to arrays at the client-side. See this Q&A.

Upvotes: 1

Related Questions