Matthew Goulart
Matthew Goulart

Reputation: 3065

How does one add data to a Chart in an ajax call?

I am trying to add data obtained from an ajax call to a chart using Chart.js.

The following code is not working:

$(document)
        .ready(function () {

            fetchBeds($("#site").val());

            var ctx = $('#paretoChart');
            var paretoChart = new Chart(ctx);

            fetchChartData(1, '2016-10-28', '2016-11-2', paretoChart);
        });


function fetchChartData(bed, start, end, chart) {

    $.ajax({
        url: "/reports/fetchChartData",
        type: "GET",
        data: {
            bed: bed,
            start: start,
            end: end

        },
        dataType: "json",
        success: function (response) {

            var chartData = {
                labels: response.data.labels,
                datasets: [{
                        label: 'Pareto of Events',
                        data: response.data.chartData,
                }]
            };

            chart.data = chartData;
            console.log(chart);
            chart.update();
        }
    });
}

When run, it doesn't generate any errors (my ajax call is working fine, verified in firefox). Simply nothing happens. I have a feeling it has to do with how I am applying the data to the chart. If I take the example data from the chart.js website and use that directly in the new Chart(...) call, it works fine.

Is it even possible to apply new data after the chart has been created?

Here is the data returned from the ajax call, just in case:

{"result":true,"message":null,"data":{"labels":["Plant","Process"],"chartData":["1","1"]}}

Thank you!

Upvotes: 0

Views: 7048

Answers (2)

Daniel Tamayo
Daniel Tamayo

Reputation: 25

Worked fine by me, see my exact code below.

You have to make sure that you are using the updated .js file of the chart.js plugin. Of course, you have to include Jquery plugin on top of your every javascript file.

For this replication, I used the cdn provided by jquery and chart.js.

<canvas id="chart" height="400px" width="400px"></canvas>

<script
  src="https://code.jquery.com/jquery-3.1.1.min.js"
  integrity="sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8="
  crossorigin="anonymous"></script>
<script     src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.3.0/Chart.bundle.js">    </script>
<script>

$.ajax({
        url: "http://localhost:8081/chart.php",
        dataType: "json",
        success: function(response)
        {
            var ctx = document.getElementById("chart");
            var myBarChart = new Chart(ctx, {
                type: 'pie',
                data: {
                    labels: response.data.labels,
                    datasets: [{
                        label: 'Number of Active Customers',
                        data: response.data.chartData,
                        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
                    }]
                }
            });
        }
});
</script>

chart.php file contains only the response JSON code as you may see below.

{
   "result":true,
   "message":null,
   "data":{
      "labels":[
         "Plant",
         "Process"
      ],
      "chartData":[
         "10",
         "1"
      ]
   }
}

Upvotes: 2

Jeshicat
Jeshicat

Reputation: 103

Alright I got the newest ChartJS and tried it out with your scenario.

My html:

<canvas id="myChart" width="200" height="200"></canvas>

Creating the chart:

$(function () {
    var ctx = $("#myChart");
    var myChart = new Chart(ctx, { type: 'bar', data: { labels: [], datasets: [] } });

     UpdateChart(myChart)
});

I had to specify the type and a data object with empty labels and datasets for it to even render on the screen as an empty chart.

My function that updates the chart:

function UpdateChart(chart) {
            var data =  {
                        labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
                        datasets: [{
                            label: '# of Votes',
                            data: [12, 19, 3, 5, 2, 3],
                            backgroundColor: [
                                'rgba(255, 99, 132, 0.2)',
                                'rgba(54, 162, 235, 0.2)',
                                'rgba(255, 206, 86, 0.2)',
                                'rgba(75, 192, 192, 0.2)',
                                'rgba(153, 102, 255, 0.2)',
                                'rgba(255, 159, 64, 0.2)'
                            ],
                            borderColor: [
                                'rgba(255,99,132,1)',
                                'rgba(54, 162, 235, 1)',
                                'rgba(255, 206, 86, 1)',
                                'rgba(75, 192, 192, 1)',
                                'rgba(153, 102, 255, 1)',
                                'rgba(255, 159, 64, 1)'
                            ],
                            borderWidth: 1
                        }]
            }
            chart.data.labels = data.labels
            chart.data.datasets = data.datasets
            chart.update()
        }

I tried doing chart.data = data but that didn't work for me. I had to specifically update data.labels then data.datasets before updating.

Upvotes: 2

Related Questions