Bar Chart With 2 Different Attribute Of The Same Variable [Chart.Js] - javascript

Good day to everyone, I am trying to display a barchart that show the count of 2 different attribute with the name 'Feedback' VS 'Complain' and these two attribute are based on user selection.
I have followed some tutorial to create a Json file to same the data retrieve from mysql then to be display on the bar chart. So this is the data.php that receives the data based on query
<?php
//setting header to json
header('Content-Type: application/json');
$mysqli = mysqli_connect('localhost','root','','customercaremodule');
if(!$mysqli){
die("Connection failed: " . $mysqli->error);
}
//query to get data from the table
$query1 = sprintf("SELECT FC_Category FROM fbcomplain where FC_Category ='Feedback'");
$Countsql1 = "SELECT count(FC_ID) AS total FROM fbcomplain WHERE FC_Category ='Feedback'";
//execute query
$result1 = $mysqli->query($query1);
$res1 = mysqli_query($mysqli,$Countsql1);
$value1 = mysqli_fetch_assoc($res1);
$feedbackrowcount = $value1['total'];
//loop through the returned data
$data1 = array();
foreach ($result1 as $row) {
$data1[] = $row;
}
//free memory associated with result
$result1->close();
//query to get data from the table
$query2 = sprintf("SELECT FC_Category FROM fbcomplain where FC_Category ='Complain'");
$Countsql2 = "SELECT count(FC_ID) AS total FROM fbcomplain WHERE FC_Category ='Complain'";
//execute query
$result2 = $mysqli->query($query2);
$res2 = mysqli_query($mysqli,$Countsql2);
$value2 = mysqli_fetch_assoc($res2);
$complainrowcount = $value2['total'];
//loop through the returned data
$data2 = array();
foreach ($result2 as $row) {
$data2[] = $row;
}
//free memory associated with result
$result2->close();
//close connection
$mysqli->close();
//now print the data
print json_encode($data1);
print json_encode($data2);
print json_encode($feedbackrowcount);
print json_encode($complainrowcount);
?>
Then here is the script function I am facing a lot of challenge with. I am very new to Chart JS and PHP in general, if there's any security flaw please bear with me. THANK YOU FOR ANY KIND HELPERS
$(document).ready(function(){
$.ajax({
url: "http://localhost/customercare/data.php",
method: "GET",
success: function(data1) {
console.log(data1);
var feedback = [];
var complain = [];
for(var i in data1) {
feedback.push(data1[i].$feedbackrowcount);
}
success: function(data2) {
console.log(data2);
var feedback = [];
var complain = [];
for(var i in data2) {
feedback.push(data2[i].$complainrowcount);
}
var chartdata = {
datasets : [
{
label: 'Feedback',
backgroundColor: 'rgba(200, 200, 200, 0.75)',
borderColor: 'rgba(200, 200, 200, 0.75)',
hoverBackgroundColor: 'rgba(200, 200, 200, 1)',
hoverBorderColor: 'rgba(200, 200, 200, 1)',
data: feedback
}
]
};
var ctx = $("#mycanvas");
var barGraph = new Chart(ctx, {
type: 'bar',
data: chartdata
});
},
error: function(data1) {
console.log(data1);
}
});
});

you can try to push in feedback an object, for example :
var bar_chart_obj_1 = {data: data1[i].$feedbackrowcount, label: "data1", id: 0};
feedback.push(bar_chart_obj_1);
var bar_chart_obj_2 = {data: $data2[i].$complainrowcount, label: "data2", id: 1};
feedback.push(bar_chart_obj_2);

Related

Javascript/PHP - Reordering JSON array randomly causes null value and deletes everything

I have a random issue while trying to reorder items in a JSON array via JS/PHP, this occurs when the array has more than 1000 items.
Example of my Users.json file:
[
{
"ID_id": "123abc",
"ST_username": "johndoe",
"ST_email": "j#example.com",
"ST_fullname": "John Doe",
},
{
"ID_id": "def345",
"ST_username": "sarahdoe",
"ST_email": "s#example.com",
"ST_fullname": "Sarah Doe",
},
{
"ID_id": "fgh567g",
"ST_username": "markdoe",
"ST_email": "mark#example.com",
"ST_fullname": "Mark Doe",
}
// + additional 1000 similar items in this array
]
So, first of all, I get the JSON file's data and decode it into a PHP array:
$tableName = $_GET['tableName']; // Lets' say $tableName is 'Users'
// fetch data from 'Users.json'
$data = file_get_contents($tableName. '.json');
$data_array = json_decode($data, true);
Then I call this function in JS:
function reorderTableData() {
var newOrderArray = [];
var data_arrayStr = JSON.stringify(<?php echo json_encode($data_array) ?>);
var jsonData = JSON.parse(data_arrayStr);
var reorderedData = JSON.stringify(jsonData, newOrderArray);
$.ajax({
url : "reorder-table-data.php",
type: 'POST',
data: 'tableName='+'<?php echo $tableName ?>'+'&reorderedData='+encodeURIComponent(reorderedData),
success: function(data) {
location.reload();
// error
}, error: function(e) {
}});
}
}
My reorder-table-data.php code:
$tableName = $_POST['tableName'];
$reorderedData = $_POST['reorderedData'];
$data_array = json_decode($reorderedData, true);
// Encode back to JSON
$data = json_encode(array_values($data_array), JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
file_put_contents($tableName. '.json', $data);
// echo JSON object
echo json_encode($data);
?>
Sometimes this code erases everything and all you see is null in the Users.json file, all data got lost.
What am I doing wrong?

Display get dynamic data in Chart.js with PHP and JS

I want to dynamically display statistics with Chart.js on my page from different users.
I can already display data with a clear data query from one user, but several identical bootstrap cards with different data should be displayed. How can I pass the user variables dynamicly to the mysqli_query in playerOne.php?
playerOne.php
header('Content-Type: application/json');
include "../../../includes/db.php";
$query = "SELECT SUM(game_stats.match_stats_kills) AS Kills, SUM(game_stats.match_stats_deaths) AS Deaths FROM game_stats WHERE game_stats.user_id = 1";
$select_kd = mysqli_query($connection, $query);
$data = array();
foreach($select_kd as $row) {
$data[] = $row;
}
mysqli_close($connection);
echo json_encode($data);
stats.js
$(document).ready(function() {
showData();
});
function showData() {
{
($.post("includes/stats/playerOne.php",
function(data) {
var kills = [];
var deaths = [];
for(var i in data) {
kills.push(data[i].Kills)
deaths.push(data[i].Deaths);
}
var pieChartData = {
labels: [
'Kills', 'Deaths'
],
datasets: [
{
backgroundColor: ['#f56954', '#00c0ef'],
data: [kills, deaths]
}
]
};
var pieChartTarget = $('#playerKD').get(0).getContext('2d');
var pieChart = new Chart(pieChartTarget, {
type: 'pie',
data: pieChartData
});
}));
}
}
you can send the variable on the url, here...
($.post("includes/stats/playerOne.php?user=1", // <-- add variable here -- ?user=1
then in your php, access the value of the variable using...
$_GET['user']
e.g.
$query = "SELECT SUM(game_stats.match_stats_kills) AS Kills, SUM(game_stats.match_stats_deaths) AS Deaths FROM game_stats WHERE game_stats.user_id = " + $_GET['user'];

Incorrect chart displayed using chart js

I am using XAMPP web server.
I have created folder chartexample in htdocs.
Now I want to display database data using chart js.
So I created data.php and bargraph.html files into chartexample folder. Similarly I created app.js file in js folder in chartexample folder.
But when I run this code undefined is display on chart. Below are my code :
data.php
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "shgreportingdatabase";
// Create connection
$conn = new mysqli($servername, $username, $password,$dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
$sql = "SELECT employee.FirstName, count(*) as TotalGroups from groupdetails, employee WHERE groupdetails.EmpId=employee.EmpId group by groupdetails.EmpId";
$result = $conn->query($sql);
if ($result!=null) {
// output data of each row
while($row = $result->fetch_assoc()) {
print json_encode($row);
}
}
$conn->close();
Here is bargraph.html
<!DOCTYPE html>
<html>
<head>
<title>ChartJS - BarGraph</title>
<style type="text/css">
#chart-container {
width: 640px;
height: auto;
}
</style>
</head>
<body>
<canvas id="mycanvas"></canvas>
<!-- javascript -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.1/Chart.min.js"></script>
<script type="text/javascript" src="js/app.js"></script>
</body>
</html>
and app.js
$(document).ready(function(){
$.ajax({
url: "http://localhost/chartexample/data.php",
method: "GET",
success: function(data) {
console.log(data);
var emp = [];
var groups = [];
for(var i in data) {
emp.push(data[i].FirstName);
groups.push(data[i].FirstName);
}
var chartdata = {
labels: emp,
datasets : [
{
label: 'SHG Groups',
backgroundColor: 'rgba(200, 200, 200, 0.75)',
borderColor: 'rgba(200, 200, 200, 0.75)',
hoverBackgroundColor: 'rgba(200, 200, 200, 1)',
hoverBorderColor: 'rgba(200, 200, 200, 1)',
data: groups
}
]
};
var ctx = $("#mycanvas");
var barGraph = new Chart(ctx, {
type: 'bar',
data: chartdata
});
},
error: function(data) {
console.log(data);
}
});
});
I suspect the problem is with your query.
$sql = "SELECT employee.FirstName, count(*) as TotalGroups from groupdetails, employee WHERE groupdetails.EmpId=employee.EmpId group by groupdetails.EmpId";
In the above, you're using WHERE to specify a link between two tables. This is a job for JOIN. You also need to specify something concrete in WHERE unless you want to get all the rows.
$SQL = "SELECT employee.FirstName, count(*) as 'TotalGroups' FROM groupdetails g JOIN employee e ON g.EmpId = e.EmpId
If you need to use a WHERE in there to exclude some data, you'll need to specify the table. For example, WHERE g.id = 5 to return ID 5 from the groupdetails table.
If you do want to return all rows, omit the WHERE clause altogether.

Google chart not getting printed in a loop

I've to show a Google Chart in a loop . Without loop my chart works fine but when i try to add it in a loop i get it only for first iterataion , how do i fix it , please review this
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Task', 'Daily Report'],
['Points Achieved', <?php echo $points_achieved?>],
['Points Left', <?php echo $points_left?>]
]);
var options = {
backgroundColor: 'transparent',
title: '' ,
chartArea:{right:0,top:0,width:"90%",height:"100%" }
,height: 150
,width: 200,
};
var chart = new google.visualization.PieChart(document.getElementById('piechart'));
chart.draw(data, options);
}
</script>
<?php
$sql= "SELECT * FROM employees";
$query= mysqli_query($connection, $sql);
while($res= mysqli_fetch_assoc($query)): ?>
<div id='piechart'></div>
//other data from database comes here
<?php endwhile;?>
Since you are drawing multiple charts i would suggest to modify drawChart function to accept chart id and data as parameters:
function drawChart(chartId,data) {
var dataTable = google.visualization.arrayToDataTable(data);
var options = {
backgroundColor: 'transparent',
title: '' ,
chartArea:{right:0,top:0,width:"90%",height:"100%" },
height: 150
,width: 200,
};
var chart = new google.visualization.PieChart(document.getElementById(chartId));
chart.draw(dataTable, options);
}
Then you could iterate PHP array and invoke drawChart function:
<?php
foreach ($reports as $key => $report) {
$chartId = "piechart_$key";
//prepare chart data
$chartData = array(
array("Task", "Daily Report"),
array("Points Achieved" , $report["Points Achieved"]),
array("Points Left" , $report["Points Left"])
);
?>
<div id='<?php echo $chartId; ?>'></div>
<script type="text/javascript">drawChart('<?php echo $chartId; ?>',<?php echo json_encode($chartData); ?>)</script>
<?php
}
?>
It is assumed $reports array has the following structure:
//input data example ( replace it with data retrieved from DB)
$reports = array(
"R1" => array("Points Achieved" => 20, "Points Left" => 4),
"R2" => array("Points Achieved" => 40, "Points Left" => 14),
"R3" => array("Points Achieved" => 10, "Points Left" => 0)
);
Working example

Insert tag “series:” into Highcharts, from the response server JSON. Malformed JSON?

This is my second question about this problem:
I try to create a chart with Highcharts, but I can not fill the field "series" with the response returned from the server with PHP. The answer is in JSON format. The chart is not rendered, it goes white background. Thank you very much in advance.
I paste her the 3 codes:
SERVER SIDE PHP:
$arr = array();
while ($row_RecordsetTabla = mysql_fetch_assoc($RecordsetTabla))
{
$fecha = $row_RecordsetTabla['fecha'];
$hora = $row_RecordsetTabla['hora'];
$estado = $row_RecordsetTabla['estado'];
$arregloFecha = date_format(new DateTime($fecha),"Y,m,d");
$arregloHora = date_format(new DateTime($hora),"H,i");
$arr[] = array("Date.UTC(".$arregloFecha.",".$arregloHora.")", $estado);
}
$arr2[] = array('data' => $arr);
$json = json_encode($arr2);
echo str_replace('"', '', $json);
RESPONSE SERVER JSON:
[{data:[[Date.UTC(2014,03,27,12,00),2],[Date.UTC(2014,04,01,19,10),1],[Date.UTC(2014,04,01,15,44),1]]}]
CLIENT SIDE JAVASCRIPT HIGHCHARTS CODE:
$.get("mostrarStatsDispositivo.php", {idDispositivo:"2", numeroDispositivo:"hola"}, function(data){
chart = new Highcharts.Chart({
chart: {
renderTo: 'divStatsDispositivo',
plotBackgroundColor: null,
plotBorderWidth: null,
plotShadow: false
},
title: {
text: 'Gráfica de actividad'
},
tooltip: {
enabled: false,
},
xAxis: {
type: 'datetime',
dateTimeLabelFormats : {
hour: '%H',
}
},
yAxis: {
categories: [ 'APAGADO', 'ACTIVO', 'ALARMA'],
title: {
text: 'ESTADO'
},
min: 0
},
series : [{
name : 'grafica',
type : 'line',
data : data[0].data //<-------thanks Barbara!
}]
});
});
The response JSON seems well formed..but dosn´t work...?¿ ....thanks!
EDIT: If i copy/paste the content of JSON in a variable, works fine. But i can´t put the value of JSON in a variable! ...doesn´t works! it´s posible?¿
FIXED!!!
Thanks Mr Jerko has detected (and solved) some errors in the code:
There is an error in a line of PHP file:
I put:
$arr2[] = array('data' => $arr);
and correct line is:
$arr2 = array('data' => $arr);
Another error to create a JSON line, and another error to put the data on "series:". check the responde under!
change your php file to look like this:
$arr = array();
while ($row_RecordsetTabla = mysql_fetch_assoc($RecordsetTabla))
{
$fecha = $row_RecordsetTabla['fecha'];
$hora = $row_RecordsetTabla['hora'];
$estado = $row_RecordsetTabla['estado'];
$arregloFecha = date_format(new DateTime($fecha),"Y-m-d");
$arregloHora = date_format(new DateTime($hora),"H:i");
$date = strtotime($arregloFecha . " " . $arregloHora) * 1000;
$arr[] = array($date, floatval($estado));
}
$arr2 = array('data' => $arr);
echo json_encode($arr2);
your JSON was in incorrect format because when you return Date.UTC(2014,03,27,12,00) without quotes it breaks format of json so you should convert your times to microseconds in php before echoing it.
also you would probably need to change your javascript line to
data: data.data

Categories

Resources