Incorrect chart displayed using chart js - javascript

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.

Related

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'];

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

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);

Chart.js - cannot fetch result from MySQL via PHP

I am trying to populate a chart via the ChartJS plugin with data from my MySQL database, but while doing so I am running into a
mysqli_fetch_assoc(): Couldn't fetch mysqli_result in ...
error.Since I am using json_encode I tried to adjust the fetch array but cant seem to figure this one out.
Any help would be much appreciated.
<div class="box-body">
<div class="chart">
<canvas id="canvas_bar" style="height:250px"></canvas>
<?php
// Start MySQLi connection
$db = new MySQLi($dbhost,$dbuser,$dbpass,$dbname);
if ($db->connect_errno) { echo "Failed to connect to MySQL: (" . $db->connect_errno . ") " . $db->connect_error; }
// count all records per month
$sql = "SELECT LOWER(MONTHNAME(mod_date)) AS mdate, count(*) AS cnt FROM qci_modreport GROUP BY LOWER(MONTHNAME(mod_date))";
if (!($result)) {
print "ERROR, something wrong with the query.";
} else {
$output = array();
while ($row = mysqli_fetch_assoc($result)) {
$output[$row['mdate']] = $row['cnt'];
}
print (json_encode($output));
}
?>
<!-- chartJS 1.0.1-->
<!-- <script src="./plugins/chartjs/Chart.js"></script> -->
<script src="../../plugins/chartjs/Chart.min.js"></script>
<script>
var barChartData = {
labels: <?php echo json_encode(array_keys($output)); ?>,
datasets: [
{
fillColor: "#03586A", //rgba(151,187,205,0.5)
strokeColor: "#03586A", //rgba(151,187,205,0.8)
highlightFill: "#066477", //rgba(151,187,205,0.75)
highlightStroke: "#066477", //rgba(151,187,205,1)
data: <?php echo json_encode(array_values($output)); ?>
}]
};
$(document).ready(function () {
new Chart($("#canvas_bar").get(0).getContext("2d")).Bar(barChartData, {
tooltipFillColor: "rgba(51, 51, 51, 0.55)",
responsive: true,
barDatasetSpacing: 6,
barValueSpacing: 5
});
});
</script>
</div>
</div>
<!-- /.box-body -->
$result is not defined. You should use
if (!($result = $db->query($sql1))) { ...
or
$result = $db->query($sql1);
and only after you do
if (!$result) { ...
and
while ($row = mysqli_fetch_assoc($result)) { ...

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

jTable Not Displaying

I'm trying to build a website including jQuery and jTable. As such, I've been trying to use the example jTable scripts that the website provides, but I can't seem to get any input returned. The file paths all work, and I check to make sure jQuery was loaded (it was). I'm really not sure what I'm doing wrong, if anything. Thanks!
jTable file:
<html>
<head>
<link href="JQueryUI/css/smoothness/jquery-ui-1.8.21.custom.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="jquery.js"></script>
<link href="jtable/themes/standard/blue/jtable_blue.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="jtable/jquery.jtable.js"></script>
</head>
<title>Under Construction</title>
Hello World
<div id="PersonTableContainer"></div>
<script type="text/javascript">
$(document).ready(function () {
$('#PersonTableContainer').jtable({
title: 'Table of people',
actions: {
listAction: 'PersonList.php'
createAction: 'CreatePerson.php'
updateAction: 'UpdatePerson.php'
deleteAction: 'DeletePerson.php'
},
fields: {
PersonId: {
key: true,
create: false,
edit: false,
list: false
},
Name: {
title: 'Author Name',
width: '40%'
},
Age: {
title: 'Age',
width: '20%'
},
RecordDate: {
title: 'Record date',
width: '30%',
type: 'date',
create: false,
edit: false
}
}
});
$('#PersonTableContainer').jtable('load');
});
PersonList.php
<?php
$link = new mysqli("localhost", "user", "pass", "people");
$query = "SELECT * FROM people";
$results = mysqli_query($link, $query);
$rows = array();
while($row = mysqli_fetch_assoc($results))
{
$rows[] = $row;
}
$jTableResult = array();
$jTableResult['Result'] = "OK";
$jTableResult['Records'] = $rows;
print json_encode($jTableResult);
}
?>
PersonList.php returns the proper output in terminal, it just doesn't seem to display anything in the website/jTable.
Try below and let me know if it works, I don't have a lot of experience with it but I even made a custom search function for it if you need it.
I use a single actions file and I use $_REQUEST for it though, not different files like you do.
//Get records from database
$result = mysql_query("SELECT * FROM people;");
//Add all records to an array
$rows = array();
while($row = mysql_fetch_array($result))
{
$rows[] = $row;
}
//Return result to jTable
$jTableResult = array();
$jTableResult['Result'] = "OK";
$jTableResult['Records'] = $rows;
print json_encode($jTableResult);
to debug this I'd start with three angles:
1. look at the AJAX response in developer tools. In Chrome that is on the Network tab, filtering by XHR. First verify that the AJAX call is being made and look at the response.
2. verify that the AJAX response is getting into the jtable context. Just add these lines under your fields attribute:
fields: {
...
},
recordsLoaded: function(event, data) {
console.log(data);
}
3. in the browser console expand this console.log object and look at the array items. jtable is case sensitive so the resulting parameters must have the same spelling and capitalization. its usually pretty easy to just change the field names in the jtable description to match the db field names.

Categories

Resources