Grails Programmer : How to integrate Chart.js to load Dynamic JSON data in a Grails 3 application?
This Gist Responsive Chart.js Example with AJAX callback inspired this article. A HTML snippet which includes JavaScript. It demonstrates how to display a graph of the library Chart.js with JSON data obtained asynchronously using jQuery.
<div class="panel panel-default">
<div class="panel-heading">Doughnut chart using displayChart() and data_1 controller action</div>
<div class="panel-body">
<button type="button" class="btn"
onClick="displayChart('/chart/data_1', '#invoice_status_chart_1')">Display Chart</button>
<div id="content" role="main" style="padding: 20px">
<canvas id="invoice_status_chart_1" width="200" height="200"></canvas>
</div>
</div>
</div>
displayChart has two arguments:
– URL used to retrieve the JSON data – jQuery selector which identifies the canvas element in which the graph will be displayed.
function createChart(selector, data) {
var ctx = jQuery(selector).get(0).getContext("2d");
new Chart(ctx).Doughnut(data);
}
function displayChart(urldata, selector) {
jQuery.get(urldata, function(data) {
var invoice_status_data = [
{
value: data.status_temp,
color: "#26292C",
highlight: "#363B3F",
label: "Temp"
},
{
value: data.status_pending,
color: "#FFA500",
highlight: "#FAD694",
label: "Pending"
},
{
value: data.status_partial,
color: "#E14D43",
highlight: "#FF5A5E",
label: "Partial"
},
{
value: data.status_complete,
color: "#76AB48",
highlight: "#86BC4A",
label: "Complete"
}
];
createChart(selector, invoice_status_data);
}
)
}
function displayChart1(urldata, selector) {
jQuery.get(urldata, function(data) {
createChart(selector, data);
}
)
}