Reputation: 81
I have started using chart.js, and I am trying to use it with Ajax. I am running in chrome and used the debugger but it is not giving me any kind of error. The problem is, I cant see the pie graph i am trying to build.
The code is all in one place as it is a test code :
<!doctype html>
<html>
<head>
<title>Pie Chart with Custom Tooltips</title>
<script src="Chart.bundle.js"></script>
<script src="jquery.js"></script>
<style>
#canvas-holder
{
width: 100%;
margin-top: 50px;
text-align: center;
}
#chartjs-tooltip
{
opacity: 1;
position: absolute;
background: rgba(0, 0, 0, .7);
color: white;
border-radius: 3px;
-webkit-transition: all .1s ease;
transition: all .1s ease;
pointer-events: none;
-webkit-transform: translate(-50%, 0);
transform: translate(-50%, 0);
}
.chartjs-tooltip-key
{
display: inline-block;
width: 10px;
height: 10px;
}
</style>
</head>
<body>
<div id="canvas-holder" style="width: 300px;">
<canvas id="chart-area2" width="300" height="300" />
</div>
<script>
$(document).ready(function() {
$.ajax({
url: "registo.php",
method: "GET",
success: function(data) {
alert(data);
var dados=[];
var score = [];
for(var i in data) {
score.push(data[i].nome_operadora);
dados.push(data[i].conta);
}
var config = {
type: 'pie',
data: {
datasets: [{
data: dados,
backgroundColor: [
"#F7464A",
"#46BFBD",
"#FDB45C",
"#949FB1",
"#4D5360",
],
}],
labels:score
},
options: {
responsive: true,
legend: {
display: false
},
tooltips: {
enabled: true,
}
}
};
var ctx2 = document.getElementById("chart-area2").getContext("2d");
new Chart(ctx2, config);
},
error: function(data) {
console.log(data);
}
});
});
</script>
The registo.php is as follows :
<?php
include "../Connections/conexao.php";
$query1 = "SELECT `op`.`nome`, COUNT(*) AS conta FROM `op` INNER JOIN `sim` ON `op`.`idcod`=`sim`.`cod_operadora` GROUP BY `op`.`idcod`
";
$result1 = mysqli_query($conexao,$query1);
$data = array();
foreach ($result1 as $row1) {
$data[] = $row1;
}
print json_encode($data);
?>
Thanks in advance
EDIT : i have solved my issue, it wasnt related to AJAX nor chart.js, but with the JSON object, I forgot to parse it.
Upvotes: 0
Views: 1219
Reputation: 81
I forgot to parse the JSON object. It is solved now
success: function(data) {
obj = JSON.parse(data);
alert(obj);
var dados=[];
var score = [];
for(var i in obj) {
score.push(obj[i].nome_operadora);
dados.push(obj[i].conta);
}
alert(score);
Upvotes: 1