[Chartjs]-Updating Chart.js with JSON, cannot read property 'length' of undefined

4👍

Seems you’re giving it the data in the wrong format. Ignoring the ajax request for now, you need to do something along the lines of:

$(document).ready(function () {
        var ctx = document.getElementById('myChart').getContext('2d');
        var chart = new Chart(ctx, {
            // The type of chart we want to create
            type: 'line',

            // The data for our dataset
            data: {
                labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July'],
                datasets: [{}]
            },
            // Configuration options go here
            options: {}
        });
        $("button").click(function () {
            chart.data.datasets = [{data: [1,2,3,4,5]}]
            chart.update()
        });
    });
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.bundle.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button>button</button>
<canvas id="myChart" >

The response you get from the request is a string, so you actually need to do:

chart.data.datasets = [{data: JSON.parse(response)}]

Leave a comment