I'm using Chartjs to create a radar chart to show scores of modules. It is working for 1 module however when I enter a 2nd module the data is placed in the same dataset causing the labels to double. The value points are also not changing name keeping the first modules point label but having different values.
This is the function used to create the graph, if the data is undefined it creates a chart but if not it adds the data to the dataset.
<script src=//code.jquery.com/jquery-3.2.1.min.js></script>
<script src=https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.bundle.js></script>
<input id=MOD_CODE value=SET08108><button id='go'>Go</button>
<canvas id="myChart" width="300" height="300"></canvas>
<script>
var data;
$(function(){
$('#go').click(function(){
$.ajax({url:'output.php', data
{MOD_CODE:$('#MOD_CODE').val()},dataType:'json', success:function(d){
if(data===undefined)
data = {labels:[],datasets:[{label:$('#MOD_CODE').val()+' Results',data:[],}]};
else
{
data.datasets.push({label:$('#MOD_CODE').val()+' Results',data:[],});
}
for(var i=0;i<d.length;i++){
data.labels.push(d[i][0]);
data.datasets[0].data.push(parseFloat(d[i][1]));
}
var ctx = document.getElementById("myChart");
var myChart = new Chart(ctx, {
type: 'radar',
data:data,
options:{
responsive:false,
scale:{ticks:{beginAtZero: true}}}});
}});
})
});
</script>
This is the the php file which gets the data based on the module code from the database, it also converts to json format for the dataset.
<?php
if(!array_key_exists('MOD_CODE',$_REQUEST)){
print "<form><input name=MOD_CODE></form>";
exit();
}
$con = new mysqli('');
if (mysqli_connect_errno()) {
printf("Connection failed: %s
", mysqli_connect_error());
exit();
}
$sql = " SELECT QUE_CODE,
100*AVG(CASE WHEN RES_VALU IN (4,5) THEN 1 ELSE 0 END) AS v
FROM INS_RES
WHERE MOD_CODE = ?
GROUP BY QUE_CODE
ORDER BY QUE_CODE
";
$stmt = $con->prepare($sql)
or die($con->error);
$stmt->bind_param('s',$_REQUEST['MOD_CODE'])
or die('Bind error');
$stmt->execute();
$res = $stmt->get_result()
or die('get_result failed: '.$con->error);
print json_encode($res->fetch_all());