Dynamic data with Chart.js
The joy of using charts on you web site!
I use chart.js and I have to say after getting MySql to extract the right data I wanted to change data dynamically without a post back to the page.
I have to say that I did find some examples online on how to do that with chart.js but the easier one to implement was to build the Chartjs object in a separate php page that you can call with an Ajax call.
<script> //global variable to remember current settings var globalDevice; var globalreadingType; $(document).ready(function(){ //on first page load set the first option on the left nav to be the first chart to display var a = $('ul[class="nav nav-pills nav-stacked"] li:first-child a')[0]; var e = document.createEvent('MouseEvents'); e.initEvent( 'click', true, true ); a.dispatchEvent(e); // jquery for click on different chart and change css $('#interval').change(function () { getChart(globalDevice, globalreadingType); }); }); //Ajax call function getChart(device, readingtype) { globalreadingType = readingtype; globalDevice = device; $("li").removeClass("active") $("#nav_" + device + readingtype).addClass('active'); $("#display").load("getChart.php?interval=" + $("#interval").val() + "&device=" + device + "&readingtype=" + readingtype); } </script>
In the code snipped above I build the ajax call depending from the values selected on the page.
The call returm the Charjs object and the div to build the char. See example below:
<div> <canvas id="canvas"></canvas> </div> <script> var timeFormat = 'MM/DD/YYYY HH:mm'; window.chartColors = { red: 'rgb(255, 99, 132)', orange: 'rgb(255, 159, 64)', yellow: 'rgb(255, 205, 86)', green: 'rgb(75, 192, 192)', blue: 'rgb(54, 162, 235)', purple: 'rgb(153, 102, 255)', grey: 'rgb(201, 203, 207)' }; var color = Chart.helpers.color; var config = { type: 'line', data: { labels: [new Date('2017-12-17 12:12:21'),new Date('2017-12-17 11:57:21'),...], datasets: [{ label: "loft_room", backgroundColor: color(window.chartColors.red).alpha(0.5).rgbString(), borderColor: window.chartColors.red, fill: false, data: [38.7500,41.2500,40.0000,38.3333,..], }] }, options: { title:{ text: "Chart.js Time Scale" }, scales: { xAxes: [{ type: "time", time: { format: timeFormat, // round: 'day' tooltipFormat: 'll HH:mm' }, scaleLabel: { display: true, labelString: 'Time' } }, ], yAxes: [{ scaleLabel: { display: true, labelString: 'Values' } }] }, } }; var ctx = document.getElementById("canvas").getContext("2d"); window.myLine = new Chart(ctx, config); </script>
Although the approch is not the most sofisticated is, in my opinion, the esiest to debug and simplest to implement. Specially if you not to familiar with the properties the Chartjs object is expecting to be passed.
Have a look at the live page here: http://home.robertomignucci.co.uk/