I am publishing the bar chart using JSON data and AJAX. The chart does not appear although no error showed in console. I am confused what is the problem because I was able to build another chart using the same way. Is there anyone can give me some clue please?
This is my codes in HTML file:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Getting Started with Chart JS with www.chartjs3.com</title>
<style>
* {
margin: 0;
padding: 0;
font-family: sans-serif;
}
.chartMenu {
width: 100vw;
height: 70px;
background: #1A1A1A;
color: rgba(255, 26, 104, 1);
}
.chartMenu p {
padding: 10px;
font-size: 20px;
}
.chartCard {
width: 100vw;
height: calc(100vh - 40px);
background: rgba(255, 26, 104, 0.2);
display: flex;
align-items: center;
justify-content: center;
}
.chartBox {
width: 700px;
padding: 20px;
border-radius: 20px;
border: solid 3px rgba(255, 26, 104, 1);
background: white;
}
</style>
</head>
<body>
<div class="chartMenu">
<p>WWW.CHARTJS3.COM (Chart JS 3.6.0)</p>
</div>
<div class="chartCard">
<div class="chartBox">
<canvas id="myChart"></canvas>
</div>
</div>
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
//Ajax Block
const xmlhttp = new XMLHttpRequest(); //exchange data with a web server
const url ='http://localhost/test/total.json';
//send a request to a server
xmlhttp.open('GET',url,true);
xmlhttp.send();
xmlhttp.onreadystatechange = function(){
if(this.readyState ==4 && this.status == 200){ //is ready and connection is success
var datapoints=JSON.parse(this.responseText); //parse:make data becomes readable in JavaScript
const male =datapoints.data.gender.male;
const female = datapoints.data.gender.female;
//setup
const data = {
labels: ['male','female'],
datasets: [{
label: 'Male',
data: male,
backgroundColor: ['rgba(255, 26, 104, 0.2)'],
borderColor: ['rgba(255, 26, 104, 1)'],
borderWidth: 1
}
,
{
label: 'Female',
data:female,
backgroundColor: ['rgba(54, 162, 235, 0.2)'],
borderColor: ['rgba(54, 162, 235, 1)'],
borderWidth: 1
}
]
};
// config
const config = {
type: 'bar',
data,
options: {
scales: {
y: {
beginAtZero: true
}
}
}
};
// render init block
const myChart = new Chart(
document.getElementById('myChart'),
config
);
}
}
</script>
</body>
</html>
This is the JSON file:
{
"data": {
"date": [
"2021-11-01",
"2021-12-31"
],
"gender": {
"male": 76,
"female": 144
},
"glasses": {
"true": 108,
"false": 112
},
"beard": {
"true": 40,
"false": 180
},
"ageGroup": {
"child": [],
"adult": 162,
"senior": 58
}
},
"success": true,
"message": ""
}