var loadingDiv = document.getElementById('loading'); var errorDiv = document.getElementById('error'); var resultDiv = document.getElementById('result'); const timeout = 10000; function getHistogram() { // Send XHR to totalTable loadingDiv.style.display = ""; errorDiv.style.display = "none"; let xhr = new XMLHttpRequest(); xhr.timeout = timeout; xhr.onreadystatechange = function() { if (xhr.readyState === XMLHttpRequest.DONE) { if (xhr.status === 200) { setData(JSON.parse(xhr.responseText)); } else { setError(); } } }; xhr.open('GET', '/histogram-data', true); xhr.send(); } function setData(data) { loadingDiv.style.display = "none"; errorDiv.style.display = "none"; var barChartData = { labels: [], datasets: [{ backgroundColor: 'rgba(54, 162, 235, 0.5)', borderColor: 'rgb(54, 162, 235, 1.0)', borderWidth: 1, label: 'Your lessons', data: [], }], }; for (let key in data) { barChartData.labels.push(data[key].time); barChartData.datasets[0].data.push(data[key].count); } let canvas = document.createElement('canvas'); let ctx = canvas.getContext('2d'); document.getElementById('result').appendChild(canvas); new Chart(ctx, { type: 'bar', data: barChartData, options: { responsive: true, legend: { position: 'top', }, title: { display: true, text: 'Histogram of times of lessons' } } }).update(); console.log(barChartData); } function setError() { loadingDiv.style.display = "none"; errorDiv.style.display = ""; } document.getElementById('tryAgain').addEventListener('click', getHistogram); getHistogram();