Javascript not getting data from PHP? - javascript

I'm trying to plot some data using javascript , ajax and php .
This is my test.php :
$query=sprintf("SELECT COUNT( `cases_title`) as count ,`cases_title` FROM `classifies` GROUP BY `cases_title`");
$result=$mysqli->query($query);
$data=array();
foreach($result as $row){
$data[]=$row;
}
$result->close();
$mysqli->close();
print json_encode($data);
?>
I printed the output and it was :
[{"count":"7","cases_title":"ANGINA"},{"count":"1","cases_title":"ASTHMA"},{"count":"4","cases_title":"MI"}]
So I suppose test.php is working.
This is my app.js :
$(document).ready(function(){
$.ajax({
url: "http://localhost/final/test.php",
method: "GET",
success: function(data) {
console.log(data);
var cas=[];
var cou=[];
// document.write(data);
for(var i in data) {
cas.push(data[i].cases_title);
cou.push(data[i].count);
}
console.log(cou);
var chartdata = {
labels: cas,
datasets : [
{
label: 'Count',
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: cou
}
]
};
var ctx = $("#mycanvas");
var barGraph = new Chart(ctx, {
type: 'bar',
data: chartdata
});
},
error: function(data) {
console.log(data);
}
});
});
document.write(data) in app.js returns : [{"count":"7","cases_title":"ANGINA"},{"count":"1","cases_title":"ASTHMA"},{"count":"4","cases_title":"MI"}]
However the arrays aren't being filled. They show as undefined . The url to test.php is correct.
What is causing the arrays cou and cas to not be filled? I couldn't figure it out.

you have to parse the response as json with JSON.parse(data) or the other side arround JSON.stringify before transferring valid json data via network.

Related

Get data from dynamic ID for Chart.js

I have created a simple chart.js line graph that can produce plots when there is a static "url" provided (Ex. localhost/test/data.php). On data.php there is a string of data that looks like this:
[{"bdi":"4","date":"2018-07-11"},{"bdi":"1","date":"2018-07-21"},{"bdi":"5","date":"2018-07-21"},{"bdi":"34","date":"2018-07-21"},{"bdi":"34","date":"2018-07-21"},{"bdi":"3","date":"2018-07-22"},{"bdi":"2","date":"2018-07-23"},{"bdi":"12","date":"2018-07-23"},{"bdi":"3","date":"2018-07-24"},{"bdi":"2","date":"2018-07-25"},{"bdi":"12","date":"2018-07-30"},{"bdi":"3","date":"2018-07-30"},{"bdi":"4","date":"2018-07-30"},{"bdi":"11","date":"2018-07-30"}]
The code for data.php looks like this:
<?php
//setting header to json
header('Content-Type: application/json');
//database
define('DB_HOST', 'localhost');
define('DB_USERNAME', 'root');
define('DB_PASSWORD', '');
define('DB_NAME', 'test');
//get connection
$mysqli = new mysqli(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_NAME);
if(!$mysqli){
die("Connection failed: " . $mysqli->error);
}
//query to get data from the table
$query = sprintf("SELECT treatment_log.bdi, treatment_log.date FROM treatment_log WHERE treatment_fk = 21 ORDER BY created_at");
//execute query
$result = $mysqli->query($query);
//loop through the returned data
$data = array();
foreach ($result as $row) {
$data[] = $row;
}
//free memory associated with result
$result->close();
//close connection
$mysqli->close();
//now print the data
print json_encode($data); ?>
Notice that the treatment_fk is 21. This means that the graph will be generated for this specific customer.
I wanted to make it so that every time you visit a cutomer.php page there will be a graph generated for that specific customer (According to their data). So I redid my coding for data.php. Instead I put the code into customer.php as a prepared statment where treatment_fk would be a variable:
<?php
$cid = htmlentities ($_GET['customer_id']);
//query to get data from the table
$sql = sprintf("SELECT treatment_log.bdi, treatment_log.date FROM treatment_log WHERE treatment_fk = ? ORDER BY created_at");
$stmt = mysqli_stmt_init($conn);
mysqli_stmt_prepare($stmt, $sql);
mysqli_stmt_bind_param($stmt, "i", $cid);
mysqli_stmt_execute($stmt);
$data = array();
mysqli_stmt_bind_result($stmt, $bdi, $date);
while(mysqli_stmt_fetch($stmt)) {
$data[]['bdi'] = $bdi;
$data[]['date'] = $date;
}
//free memory associated with result
$result->close();
//now print the data
print json_encode($data); ?>
So now, every time you visit a unique customer with different ID's (in the url) a different string of data will be generated on the customer.php page.
Now the issue that I am facing is that I cannot successfully generate the line graph based on this string of data (bdi vs date).
Here is my code of the chart.js graphing field:
$(document).ready(function(){
$.ajax({
url: "http://localhost/test/data.php",
method: "GET",
success: function(data) {
console.log(data);
var bdi = [];
var date = [];
for(var i in data) {
date.push( data[i].date);
bdi.push(data[i].bdi);
}
var chartdata = {
labels: date,
datasets : [
{
label: 'BDI',
backgroundColor: 'rgba(239, 243, 255, 0.75)',
borderColor: 'rgba(84, 132, 255, 0.75)',
hoverBackgroundColor: 'rgba(200, 200, 200, 1)',
hoverBorderColor: 'rgba(200, 200, 200, 1)',
data: bdi
}
]
};
var ctx = $("#mycanvas");
var barGraph = new Chart(ctx, {
type: 'line',
data: chartdata,
options: {
responsive: true,
legend: {
position: 'bottom',
},
scales: {
yAxes: [{
ticks: {
fontColor: "rgba(0,0,0,0.5)",
fontStyle: "bold",
beginAtZero: true,
maxTicksLimit: 5,
padding: 20
},
gridLines: {
drawTicks: false,
drawBorder: false,
}
}],
xAxes: [{
gridLines: {
zeroLineColor: "transparent",
display: false
},
ticks: {
padding: 20,
fontColor: "rgba(0,0,0,0.5)",
fontStyle: "bold"
}
}]
},
tooltips: {
backgroundColor: 'rgba(255,255,255)',
titleFontColor: 'rgb(184,189,201)',
bodyFontColor: 'black',
displayColors: false,
borderColor: 'rgb(214,217,225)',
borderWidth: 1,
caretSize: 5,
cornerRadius: 2,
xPadding: 10,
yPadding: 10
}
}
});
},
error: function(data) {
console.log(data);
}
});
});
Notice that the URL is http://localhost/test/data.php.
Although this does generate graph, it is not a graph specific to the customer. I have tried to replace the url with http://localhost/test/view_customer?customer_id=12&operation=edit (to test if a change in URL would work). However, it still does not generate a graph. Keep in mind that when I visit http://localhost/test/view_customer?customer_id=12&operation=edit in the source code, there is a string of data bdi vs. date. Regardless a graph is still not generated.
Here is my question:
1. How do I make the URL dynamic so that I generates a graph based on the specific ID of the customer.php? (Is there a better way?)
P.s. remember that http://localhost/test/view_customer?customer_id=12&operation=edit did not generated a graph when it was placed as the url in chart.js code.
You are not creating the same type of array on customer.php as you are on data.php. Replace your while loop in customers with the below and you should have the same format of JSON.
while(mysqli_stmt_fetch($stmt)) {
$data[] = array('bdi' => $bdi, 'date' => $date);
}

Chart.js with data from database

since 2 hours I'm trying a simple thing: displaying data from database with Chart.js. I've checked like 4 tutorials, viewed 3 SO-Threads, but nothing is working as intented to. Don't know if its just a minor problem or what the problem is...
So what I'm trying is the following:
stats.php:
<script>
function getRandomColor() {
var letters = '0123456789ABCDEF';
var color = '#';
for (var i = 0; i < 6; i++) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
}
</script>
<script>
$(document).ready(function(){
$.ajax({
url: "stats_api.php",
method: "GET",
success: function(data) {
console.log(data);
var chart = new Chart(document.getElementById("pie-chart"), {
type: 'pie',
data: {
labels: data,
datasets: [{
label: "Anzahl Asservate",
backgroundColor: [getRandomColor(),getRandomColor(),getRandomColor(),getRandomColor(),getRandomColor(),getRandomColor(),getRandomColor(),getRandomColor(),getRandomColor(),getRandomColor()],
data: [1,2,3,4,5,6,7,8,9,10],
}]
},
options: {
title: {
display: true,
text: 'Kategorien-Verteilung der Asservate'
}
}
});
}
});
});
</script>
stats_api.php:
<?php
require 'databaseConnection.php';
$datumStart = "2010-12-19 08:38:32";
$datumEnde = "2019-12-19 08:38:32";
$v_rp_ass_kat = $database->query("
select s.* from (select #DatumStart:='$datumStart',#DatumEnde:='$datumEnde') parm , v_rp_ass_kat s;")->fetchAll();
$labels = [];
foreach($v_rp_ass_kat as $element){
array_push($labels, $element[2]);
}
echo json_encode($labels);
The json_encode is returning this:
["Mobiltelefon","Smartphone","SIM-Karte","Tablet","Navigationsger\u00e4t","USB-Stick","Speicherkarte","PC","Notebook","Festplatte"]
With that, I'm getting the error saying data.labels.map is not a function.
I also tried it without the foreach in php, instead a json_encode of $v_rp_ass_kat and then do a
labels = [];
for(var i in data){
labels.push(data[i].kategorie);
}
But this somehow splits the array into single letters, so instead of 10 labels with one word each, I get like 100 labels, one for every letter of the json array...
What do I do wrong?
I reckon, you're getting the response as a string and passing it to the labels property, while it expects an array of strings. (same mistake in your fiddle as well)
To convert that response string to an array, you can use JSON.parse()
...
data: {
labels: JSON.parse(data),
...
also, you should use the chart.js version 2.x, as you're using it's syntax.
Working fiddle - https://jsfiddle.net/bf4v9272/5/
https://www.dyclassroom.com/chartjs/chartjs-how-to-draw-bar-graph-using-data-from-mysql-table-and-php
$(document).ready(function(){
$.ajax({
url: "http://localhost/chartjs/data.php",
method: "GET",
success: function(data) {
console.log(data);
var player = [];
var score = [];
for(var i in data) {
player.push("Player " + data[i].playerid);
score.push(data[i].score);
}
var chartdata = {
labels: player,
datasets : [
{
label: 'Player Score',
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: score
}
]
};
var ctx = $("#mycanvas");
var barGraph = new Chart(ctx, {
type: 'bar',
data: chartdata
});
},
error: function(data) {
console.log(data);
}
});
});
i hope you will Get

Bar Graph, chart.js PHP Will Not Load

I have a bar graph that I'm attempting to create with chart.js that takes a PHP array and loads via ajax. I am able to load the data with ajax (verified in the console) but I cannot get the data in the graph - here is the data in the console:
I have not received any error messages so I'm perplexed at this point. Here is all of the code:
HTML
<?php
include 'connect.php';
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
</head>
<body>
</canvas><canvas id="myChart"></canvas>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script src="javascript/charts.js" type="text/javascript"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js"></script>
</body>
JS
$(document).ready(function(){
$.ajax({
url: "prod_agg.php",
method: "GET",
success: function(data) {
console.log(data);
var date = [];
var output = [];
for(var i in data) {
date.push(data[i].date);
output.push(data[i].output);
}
var chartdata = {
labels: date,
datasets : [
{
label: 'Date',
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: output
}
]
};
var ctx = $("#myChart");
var barGraph = new Chart(ctx, {
type: 'bar',
data: chartdata
});
},
error: function(data) {
console.log(data);
}
});
});
I receive an empty graph:
Any help on this issue would be greatly valued!
The reason it's not working is because, you are getting the response data as a JSON string not JSON object.
So, to make it work with ChartJS, you need to parse it first, using JSON.parse() method ...
$(document).ready(function() {
$.ajax({
url: "prod_agg.php",
method: "GET",
success: function(data) {
console.log(data);
var data = JSON.parse(data); //parse JSON string
var date = [];
var output = [];
...

Undefined values in chart.js from json

i am working on showing data in a bar chart with chart.js . my json response is already ready there but chart says its undefined values.
here is jquery with json
$(document).ready(function(){
$.ajax({
url: "<?php base_url();?>/charts/getsome",
method: "GET",
success: function(data) {
console.log(data);
var month = [];
var customers = [];
for(var i in data) {
month.push("Customer in" + data[i].apply_month);
customers.push(data[i].no_customers);
}
var chartdata = {
labels: month,
datasets : [
{
label: 'monthly customers',
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: customers
}
]
};
// alert(chartdata);
var ctx = $("#mycanvas");
var barGraph = new Chart(ctx, {
type: 'bar',
data: chartdata
});
},
error: function(data) {
console.log(data);
}
});
});
below is a snap for json response in console
And here is also a snap for chart with error
Please guide me where i am wrong. Thanks
You are getting response as a string. you should parse using JSON.parse(data)
success: function(data) {
console.log(data);
data = JSON.parse(data)
//the rest of your code
}

How to correctly passed php mysql data to ChartJs

I want to be able to produce bar chart and pie charts using ChartJs. I'm using php and mysql to get the data. The bar chart that I want to produce is a chart that shows the stats of students who are male or female and the sum of students also. Here is an example of how I want the result to appear:
It may not be exactly like it, but I feels it gives an idea. I'm problems with my code which I don't seem to understand, because I'm a novice to ChartJs and is just trying it out, since morris.js isn't being fully supported. Here is how my code looks:
Html
<div class="box box-success">
<div class="box box-header with-border">
<h3 class="box-title">Student Chart</h3>
<div class="box-tools pull-right">
<button type="button" class="btn btn-box-tool" data-widget="collapse"><i class="fa fa-minus"></i>
</button>
<button type="button" class="btn btn-box-tool" data-widget="remove"><i class="fa fa-times"></i></button>
</div>
<div class="box-body">
<canvas id="mycanvas" style="height:230px;"></canvas>
</div>
</div>
Script:
$.ajax({
url: 'data.php',
type: 'GET',
success:function(data){
console.log(data);
var male = [];
var female = [];
for(var count in data){
male.push(data[count].male);
female.push(data[count].female);
}
var chartdata = {
labels: male,
datasets: [
{
label: 'Student Gender',
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:female
}
]
};
var ctx = $('#mycanvas');
var barGraph = new Chart(ctx, {
type:'bar',
data: chartdata
});
},
error:function(data){
console.log(data);
}
});
data.php
$query = "SELECT
SUM(CASE WHEN gender = 'Male' THEN 1 ELSE 0 END) as Male,
SUM(CASE WHEN gender = 'Female' THEN 1 ELSE 0 END) as Female
FROM students";
$output = array();
if ($result = mysqli_query($connection, $query)) {
# code...
foreach ($result as $row) {
# code...
$output[] = $row;
}
} else {
die("There was a problem". mysqli_error($connection));
}
echo json_encode($output);
Here is the result I'm getting from the console:
[{"Male":"5","Female":"2"}]
Will appreciate suggestion on how I can make it better and do the same for pie chart also.
Based on what I've done this is how my chart is displaying:
Note Please ignored the frequency on the photo.
Would suggest you to change your sql query to following.
$query = "select gender,count(gender) as count from students group by gender";
$output = array();
if ($result = mysqli_query($connection, $query)) {
# code...
foreach ($result as $row) {
# code...
$output[] = $row;
}
} else {
die("There was a problem". mysqli_error($connection));
}
echo json_encode($output);
script:
$.ajax({
url: 'data.php',
type: 'GET',
success:function(data){
console.log(data);
var gender = [];
var sum = [];
for(var count in data){
gender.push(data[count].gender);
sum.push(data[count].total);
}
var chartdata = {
labels: gender,
datasets: [
{
label: 'Student Gender',
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:sum
}
]
};
var ctx = $('#mycanvas');
var barGraph = new Chart(ctx, {
type:'bar',
data: chartdata
});
},
error:function(data){
console.log(data);
}
});
I realize that the problem was with my script. Big thanks to #milan kumar for helping with the query. What was missing was specification of the type of data I was sending to ajax. All I had to do was to add the dataType with value 'json' before the success function, and it work perfectly. This is how the code should look:
script:
$.ajax({
url: 'data.php',
type: 'GET',
// this was what I needed to make it work.
dataType: 'json',
success:function(data){
var gender = [];
var sum = [];
for(var i in data){
gender.push(data[i].gender);
sum.push(data[i].total);
}
var ChartData = {
labels: ['Student Gender'],
datasets: [
{
label: gender[0],
fillColor: "rgba(210, 214, 222, 1)",
strokeColor: "rgba(210, 214, 222, 1)",
pointColor: "rgba(210, 214, 222, 1)",
pointStrokeColor: "#c1c7d1",
pointHighlightFill: "#fff",
pointHighlightStroke: "rgba(220,220,220,1)",
data:sum[0]
},
{
label: gender[1],
fillColor: "rgba(60,141,188,0.9)",
strokeColor: "rgba(60,141,188,0.8)",
pointColor: "#3b8bba",
pointStrokeColor: "rgba(60,141,188,1)",
pointHighlightFill: "#fff",
pointHighlightStroke: "rgba(60,141,188,1)",
data:sum[1]
}
]
};
});
I have added some optional attributes to beautify my chart.

Categories