NiceToMytyuk
NiceToMytyuk

Reputation: 4277

ChartJS chart is bugged after adding new data

Actually in my website i build a char with some data from MySQL Database.

Every time the chart button is pressed a modal will appear an AJAX call will be sent to the server and then the Chart will be drawn.

The issue is that after adding new data to database and by opening the modal with the ChartJS by moving the mouse the ChartJS tilt between chart with new data and the old one.

enter image description here

Here is the code

var chart;

$(function () {
    renderChart();
});


function renderChart() {
    var ctx = document.getElementById('barchart').getContext('2d');
    var gradient = ctx.createLinearGradient(0, 0, 0, 400);
    gradient.addColorStop(0, '#007AFD');
    gradient.addColorStop(1, '#00B1FF');
    var options = {
        legend: false,
        maintainAspectRatio: false,
        tooltips: {
            displayColors: false
        },
        scales: {
            xAxes: [{
                gridLines: {
                    display: false,
                },
                barPercentage: 0.3,
            }],
            yAxes: [{
                ticks: {
                    stacked: true,
                    stepSize: 1,
                    beginAtZero: true,
                },
                gridLines: {
                    borderDash: [5, 15],
                    drawBorder: false
                }
            }]
        }
    };
    chart = new Chart(ctx, { type: 'bar', labels: [], data: [] });
}

function loadReports(data) {
    $.ajax({
        type: "POST",
        url: "Default.aspx/getReports",
        contentType: "application/json; charset=utf-8",
        data: JSON.stringify({ data: data }),
        dataType: "json",
        success: function (r) {
            data = r.d;
            if (data != '[]') {
                data = jQuery.parseJSON(data);
                chart.data.labels = data.map(ora => ora.ORARIO);
                chart.data.datasets[0].data[0] = data.map(cop => cop.COPERTI);
                chart.update();
            } else {
                chart.data.labels = [];
                chart.data.datasets[0].data = [];
                chart.update();
            }

        },
        error: function (error) {
            alert(error.responseText);
        }
    });

}

buildChart() is called on load and chart is declared on top of JS file

Upvotes: 0

Views: 406

Answers (1)

Ilijanovic
Ilijanovic

Reputation: 14904

Are you drawing a new chart by clicking on the button? You should draw your chart just 1 time and then update the data:

function addData(chart, label, data) {
chart.data.labels.push(label);
chart.data.datasets.forEach((dataset) => {
    dataset.data.push(data);
  });
  chart.update();
}

function removeData(chart) {
    chart.data.labels.pop();
    chart.data.datasets.forEach((dataset) => {
        dataset.data.pop();
    });
    chart.update();
}

Docs: https://www.chartjs.org/docs/latest/developers/updates.html

you can try it with this code:

 $.ajax({
  type: "POST",
  url: "Default.aspx/getReports",
  contentType: "application/json; charset=utf-8",
  data: JSON.stringify({ data: data }),
  dataType: "json",
  success: function(r) {
    data = r.d;
    if (data != "[]") {
      data = jQuery.parseJSON(data);
      chart.data.labels = data.map(ora => ora.ORARIO);
      chart.data.datasets[0].data = data.map(coperti => coperti.COPERTI);
      chart.update();
    } else {
      chart.data.labels = [];
      chart.data.datasets[0].data = [];
      chart.update();
    }
    $("#modalChart").modal("show");
  },
  error: function(error) {
    alert(error.responseText);
  }
});

Upvotes: 2

Related Questions