0

I am loading a chart using Chart.js with hard coded data when the page starts. Following that upon a button click, I am making an ajax query; get external data from database and want to load that data into the chart.

I have the correct data retrieved and stored as an array. I want to clear the current chart data and input this new array as new data for the chart.

For starters I would need to empty the old data and tried, clear() and destroy() and neither of them works. The chart just keeps reloading with the old data. The old chart seems removed for a split second only to see it reappear. How can I resolve this?

 $( document ).ready(function() {

        var lineData = {
            labels: ["Lap 1", "Lap 2", "Lap 3", "Lap 4", "Lap 5"],
            datasets: [{
                fillColor: "rgba(255,255,255,0)",
                strokeColor: "rgba(63,169,245,1)",
                pointColor: "rgba(63,169,245,1)",
                pointStrokeColor: "#fff",
                data: [10, 20, 30, 40, 55] // need to swap this with race1Data array
            }, {
                fillColor: "rgba(255,255,255,0)",
                strokeColor: "rgba(102,45,145,1)",
                pointColor: "rgba(102,45,145,1)",
                pointStrokeColor: "#fff",
                data: [97, 87, 55, 72, 66]
            }]
        }

        var lineOptions = {
            responsive: true,
            animation: true,
            pointDot: true,
            scaleOverride : false,
            scaleShowGridLines : false,
            scaleShowLabels : true,
            scaleSteps : 4,
            scaleStepWidth : 25,
            scaleStartValue : null
        };

        //Create Line chart
        var ctx = document.getElementById("lineChart").getContext("2d");
        myNewChart = new Chart(ctx).Line(lineData, lineOptions);

        $("#form").submit(function(e) {
        var race1 = $( "#racename1" ).val();
        var race2 = $( "#racename2" ).val();
        var race1Data = [];
            $.post("MyServlet", {raceName1 : race1, raceName2 : race2},  function(responseText) {
                race1Data = responseText; // <-- correct data
                myNewChart.destroy(); // <--doesn't work
            });
        });

    });    
JasSy
  • 583
  • 5
  • 17

1 Answers1

1

I didn't find any better solution but to iterate through the lineData and remove all the data by calling removeData()

Here's the example created for the code provided: https://jsfiddle.net/4e3u5L89/2/

Evgeny Sorokin
  • 630
  • 3
  • 12