[Chartjs]-Passing Data from Controller to ChartJS

1๐Ÿ‘

โœ…

I faced similar problem and found that we should use Object.keys(data) instead of data.keySet(). So below is the way you can use it

var htmldata = [[${data}]];
var ctx = document.getElementById('myChart').getContext('2d');
    var myChart = new Chart(ctx, {
        type: 'pie',
        data: {
            labels: Object.keys(htmldata),
            datasets: [{
                data: Object.keys(htmldata).map(function(key) {return htmldata[key];}),
                backgroundColor: [
                    'rgb(0,255,255)',
                    'rgb(46,139,87)',
                    'rgb(255,165,0)'
                ],
                borderColor: [
                    'rgb(0,255,255)',
                    'rgb(46,139,87)',
                    'rgb(255,165,0)'
                ],
                borderWidth: 1
            }]
        },
    });

Also your javascript is not thymeleaf readable. Please add th:inline=javascript in script tag and provide CDATA as below

<script th:inline="javascript">   
  /*<![CDATA[*/
       // Here goes my previous script
  /*]]>*/
</script>

0๐Ÿ‘

There is a simpler solution. Just generate your LinkedHashMap like this:

graphDataHM.put('"'+yourLabel+'"', yourValue);

Then in the HTML code use:

<pre>
<body>
<div class="container">
    <div th:replace="fragments/navbar :: top"></div>

    <div class="row" style="margin-top: 60px">

        <div class="chart-container" style="margin: 0 auto; height:20vh; width:40vw">
            <canvas id="myChart"></canvas>
        </div>
        <script>
        var xValues = ${graphDataHM.keySet()};
        var yValues = ${graphDataHM.values()};

        var ctx = document.getElementById('myChart').getContext('2d');
        var myChart = new Chart(ctx, {
            type: 'pie',
            data: {
                labels: xValues,
                datasets: [{
                    data: yValues,
                    backgroundColor: [
                        'rgb(0,255,255)',
                        'rgb(46,139,87)',
                        'rgb(255,165,0)'
                    ],
                    borderColor: [
                        'rgb(0,255,255)',
                        'rgb(46,139,87)',
                        'rgb(255,165,0)'
                    ],
                    borderWidth: 1
                }]
            },
        });
        </script>

    </div>

</div>

</body>
</pre>

You can populate your LinkedHashMap with data from any source (database, other objects and so on).

Leave a comment