PHP: chart_db.php
<?php
require_once ('dbh.inc.php');
$JSON_Response = array();
//Counts the number of Active
$count_active = mysqli_query($db, "SELECT client_id FROM client WHERE status = 1");
$JSON_Response['active'] = mysqli_num_rows($count_active);
//Counts the number of Inactive
$count_inactive = mysqli_query($db, "SELECT client_id FROM client WHERE status = 0");
$JSON_Response['inactive'] = mysqli_num_rows($count_inactive);
error_log('hello');
echo json_encode($JSON_Response);
?>
JS: chart.js
$(document).ready(function(){
$.ajax({
url:"http://localhost/FAME/private/includes/chart_db.php",
method: "GET",
success: function(response){
var data = JSON.parse(response);
var activeData = text(data.active);
var inactiveData = text(data.inactive);
console.log(activeData);
var ctx = document.getElementById('piechart').getContext('2d');
var statusChart = new Chart(ctx, {
type: 'doughnut',
data: {
labels: ['Active', 'Inactive'],
datasets: [{
pointStyle: 'circle',
backgroundColor: [ 'rgb(78, 115, 223)', 'rgb(25, 179, 211)' ],
data: activeData, inactiveData
}]
},
options: {
responsive: true,
maintainAspectRatio: false,
segmentShowStroke: false,
cutoutPercentage: 70,
legend: {
onClick: false,
position: 'bottom',
labels: {
usePointStyle: true
}
}
}
});
}
});
});
Question: The problem is that in the data in chart are not showing. The entire chart is not showing. And with the log from chrome inspection: it says that there is an error: "Uncaught ReferenceError: text is not defined".
This has nothing to do with php, mysql or xampp. You are using an undefined method called text. The error message says it all. Check your third and fourth lines in the ajax success. You have:
var activeData = text(data.active);
Replace it with :
var activeData = data.active;
and see what happens.
Related
I want to create a bar chart using chartjs,PHP and MySql. After querying the database to get product details as a json object, now I want to iterate over the array and add product_name and price into new arrays, of which I get undefined. What might be wrong to my code?
$(document).ready(function(){
$.ajax({
url: "../controller/products-chart-data.php",
method: "GET",
success: function(data){
console.log(data);
var product = [];
var price = [];
for (var i in data) {
product.push(data[i].product_name);
price.push(data[i].price);
}
var chartData = {
labels: product,
datasets: [
{
label: "Product Price",
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: price
}
]
};
var context = $("#products-chart");
var barGraph = new Chart(context, {
type: 'bar',
data: chartData
});
},
error: function(data){
console.log(data);
}
})
})
PHP code for the database query:
<?php
$conn = mysqli_connect('localhost', 'root', '', 'shopping_cart_with_paypal');
$getAllproductsQuery = $conn->query("SELECT * FROM tbl_products");
$data = array();
foreach ($getAllproductsQuery as $row) {
$data[] = $row;
}
$getAllproductsQuery->close();
$conn->close();
print json_encode($data);
Sample data:
[{"id":"3","product_name":"Travel
bag","price":"5000","category_id":"1","product_image":"travel-
bag.jpeg","average_rating_id":"3","description":"Lather travel bag, found in
different sizes","product_code":"203"},{"id":"4","product_name":"Jewel
Box","price":"6000","category_id":"4","product_image":"jewel-
box.jpeg","average_rating_id":"5","description":"Modern jewel box straight
dubai","product_code":"204"},{"id":"5","product_name":"Wooden
Dolls","price":"9000","category_id":"5","product_image":"wooden-
dolls.jpeg","average_rating_id":"3","description":"wooden dolls made of pure
woods","product_code":"205"}]
I would like to make charts using ChartJS and PHP ( Silex Framework )
This is my ajax call
$.ajax({ url: 'stats',
data: {method: 'dossierRepartitionType'},
type: 'post',
datatype: 'json',
success: function(output) {
dataDossierRepartitionType=output;
},
error: function () {
alert("Oops there is an error.");
}});
This is my PHP function which i managed to call
public function dossier(){
$stmt = "SELECT count(*) FROM dossier GROUP BY typedossier";
$stmt = $this->db->prepare($stmt);
$rows=$stmt->execute();
$rows = $stmt->fetch(PDO::FETCH_NUM);
return ?????
}
And here is my chart :
var ctx = document.getElementById("myChart");
ctx.width = 400;
ctx.height = 400;
data = {
datasets: [{
data: [dataDossierRepartitionType, 20],
backgroundColor: [
'rgb(255, 99, 132)',
'rgb(54, 162, 235)',
],
borderColor: [
'white',
'white',
],
borderWidth: 1
}],
// These labels appear in the legend and in the tooltips when hovering different arcs
labels: [
'Red',
'Blue',
]
};
var myDoughnutChart = new Chart(ctx, {
type: 'doughnut',
data: data,
options: {
legend: {
labels: {
fontColor: "white",
fontSize: 18
}
},
maintainAspectRatio: false,
responsive: false
}
});
Route.php
$app->post('/stats', function () use ($app) {
session_start();
if(isset($_POST['method']) && !empty($_POST['method'])) {
$method = $_POST['method'];
switch($method) {
case 'dossierRepartitionType' :
$dossiers=$app['dao.dossier']->dossierRepartitionType();
break;
}
}
return new ResponseSilex("$dossiers");
});
So my AJAX call the route and then get the result of the function into $dossiers which is ouput in the Reponse, am i doing it right ?
How can i return an array with all the datas value for each count ?
I struggle to catch error and to find a proper way to bind MYSQL count value to my chart
Thank you
The main idea is that you should format your data in your model, then return JSON to the front end via json_encode. After that, you would parse the json in your ajax returns and then pass the appropriate data to the chart.
it's very easy, you need to modify your php code like this:
public function dossier(){
$stmt = "SELECT count(*) as total FROM dossier";
$stmt = $this->db->prepare($stmt);
$rows=$stmt->execute();
$number_of_rows = $rows->fetchColumn();
return json_encode(["total" => $number_of_rows]);
In your ajax petition you are specifying a "json" return so in your script php need's return a json.
$.ajax({ url: 'stats',
data: {method: 'dossierRepartitionType'},
type: 'post',
datatype: 'json',
success: function(output) {
dataDossierRepartitionType=output.total;
},
error: function () {
alert("Oops there is an error.");
}});
You should to receive a json from php with this structure
{total: rows_total}
so in your ajax response you'll receive that answer and you can get the data like this:
dataDossierRepartitionType=output.total;
Sorry for my english, hope can help you
You can send JSON data from php
Try this:
Php:
public function dossier(){
$stmt = "SELECT count(*) FROM dossier GROUP BY typedossier";
$stmt = $this->db->prepare($stmt);
$rows=$stmt->execute();
$rows = $stmt->fetch(PDO::FETCH_NUM);
exit(json_encode(array('counts' => $rows)));
}
After ajax successfully complete you need to initialize chart plugin inside success callback like below:
Ajax:
$.ajax({ url: 'stats',
data: {method: 'dossierRepartitionType'},
type: 'post',
datatype: 'json',
success: function(output) {
if (output.counts) {
dataDossierRepartitionType=output.counts.join();
alert(dataDossierRepartitionType)
initCharts(dataDossierRepartitionType);
}
},
error: function () {
alert("Oops there is an error.");
}});
Finally wrap chart initialization code inside callback function
Chart:
function initCharts(dataDossierRepartitionType){
var ctx = document.getElementById("myChart");
ctx.width = 400;
ctx.height = 400;
data = {
datasets: [{
data: [dataDossierRepartitionType, 20],
backgroundColor: [
'rgb(255, 99, 132)',
'rgb(54, 162, 235)',
],
borderColor: [
'white',
'white',
],
borderWidth: 1
}],
// These labels appear in the legend and in the tooltips when hovering different arcs
labels: [
'Red',
'Blue',
]
};
var myDoughnutChart = new Chart(ctx, {
type: 'doughnut',
data: data,
options: {
legend: {
labels: {
fontColor: "white",
fontSize: 18
}
},
maintainAspectRatio: false,
responsive: false
}
});
}
Line chart is drawn very fine using (int) values using Google Charts API (see exact below code) but one of the percentage column value is in float so I tried (floatval) instead of (int) but PHP server file throws 500 internal server error.
What is the solution in especially at to use float value?
(int)str_replace("%", "", $row['percentage'])
Also note that, my values are coming as JSON from MySQL.
PHP (server file):
$rows[] = array(explode(" - ", $row['started_on'])[0].trim(), 'Coverage');
while($row = mysqli_fetch_array($result)) {
$rows[] = array(explode(" - ", $row['started_on'])[0].trim(), (int)str_replace("%", "", $row['percentage']));
}
JS (in php):
// Draw line chart
function drawLineChart(chartType, chartTitle) {
google.charts.setOnLoadCallback(lineChartData);
function lineChartData() {
var lineChartJsonData = $.ajax({
type: 'GET',
url: "<?php echo $general_scripts; ?>",
data: { id1: chartType, id2: "Chart", id100: "<?php echo $getPage; ?>" },
dataType:"json",
async: false,
beforeSend: function() {
$("#progress").show();
},
success: function(data) {
$("#progress").hide();
},
}).responseText;
var options = {
title: chartTitle,
width: '390',
height: '300',
backgroundColor: '#f5fffa',
};
var data = new google.visualization.arrayToDataTable(($.parseJSON(lineChartJsonData)));
var chart = new google.visualization.LineChart(document.getElementById(chartType));
chart.draw(data, options);
}
}
(float) works fine, here it is:
$rows[] = array(explode(" - ", $row['started_on'])[0].trim(), (float)str_replace("%", "", $row['data']));
echo json_encode($rows);
Give this data to chart.draw(data, options);
I am trying to build column based highcharts, and here is my code in jquery:
var options = {
chart: {
renderTo: 'container',
type: 'column'
},
credits: {
enabled: false
},
title: {
text: 'PCP Histogram',
x: -20
},
xAxis: {
categories: [{}]
},
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'top',
x: -10,
y: 100,
borderWidth: 0
},
tooltip: {
formatter: function() {
var s = '<b>'+ this.x +'</b>';
$.each(this.points, function(i, point) {
s += '<br/>'+point.series.name+': '+point.y;
});
return s;
},
shared: true
},
series: [{},{}]
};
$.ajax({
url: "file.php",
type: "post",
dataType: "json",
success: function(data){
options.xAxis.categories = data.categories;
options.series[0].name = 'Avg1';
options.series[0].data = data.avg1;
options.series[1].name = 'Avg2';
options.series[1].data = data.avg2;
var chart = new Highcharts.Chart(options);
And I getting the data from file php like this:
file.php
$graph_data = array('categories'=>$categories, 'avg1'=>$avg, 'avg2'=>$avg);
print json_encode($graph_data, JSON_NUMERIC_CHECK);
It is working fine with two columns per category,
What I want now is: the graph_data can have n number of avg datas,
so basically it will be n number of columns.
$graph_data = array('categories'=>$categories, 'avg1'=>$avg1, ... 'avgn'=>$avgn);
When I do it manually it works, but I will not know how many of them will be there, so I want the code to do i.
Any idea how I can do it?
Any help appreciated.
make an array of avg instead of having avg1, avg2 etc....
$graph_data = array('categories'=>$categories, 'avgs'=>$array_of_avgs)
then in javascript side
success: function(data){
options.xAxis.categories = data.categories;
for(var i in data.avgs){
options.series[i].name = 'Avg'+i;
options.series[i].data = data.avgs[i];
}
var chart = new Highcharts.Chart(options);
And everything will be fine
I'm trying to create a chart using data from my database calling json, but its not showing the results in the chart.
Here's my code so far:
$(document).ready(function() {
function requestData() {
$.ajax({
url: 'data.php',
datatype: 'json',
success: function(data) {
alert(data);
chart.series[0].setData(data[0]);
},
cache: false
});
}
var chart;
chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
type: 'line',
events: {
load: requestData
}
},
xAxis: {
},
yAxis: {
title: {
text: 'Value'
}
},
series: [{
name: 'Random data',
data: []
}]
});
});
And here's my data.php code
$query = "SELECT tiempo,Fp1Ref
FROM GraficaEEG limit 10";
$data = mysqli_query($dbc, $query);
$i=0;
while($row = mysqli_fetch_array($data)) {
$row['tiempo'] = (float) $row['tiempo'];
$rows[$i]=array($row['tiempo'],(float)$row['Fp1Ref']);
$i++;
}
echo json_encode($rows);
The data i receive is this:
[[0,3001],[0.005,4937.22],[0.01,4130.55],[0.015,4213.15],[0.02,4010.61],[0.025,3914.34],[0.03,3785.33],[0.035,3666.13],[0.04,3555.25],[0.045,3447.77]]
So i think is the proper way to pass data for the chart, so i don't quite get whats wrong, thank you in advance.
I think the problem is that when your requestData() function is fired the chart variable still isn't fully built and doesn't know it has the series property.
To fix this, instead of chart in your requestData() function, reference this (which means the chart object in that context).
I tried this out in jsfiddle here http://jsfiddle.net/elcabo/p2r6g/.
Also post the js code below.
$(function () {
$(document).ready(function() {
//Function bits
function requestData(event) {
var tiemposAlAzar = [[10,20],[20,50]];
//The 'this' will refer to the chart when fired
this.series[0].setData(tiemposAlAzar);
};
var chart;
//Chart bits
chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
type: 'line',
events:{
load: requestData
}
},
xAxis: {},
yAxis: {
title: {
text: 'Value'
}
},
series: [{
name: 'Random data',
data: []
}]
});
});
});
This url may help you to create dynamic highchart that need to pull data from database.
In json.php code you can put your sql query and replace static array to dynamic array
http://www.kliptu.com/free-script/dynamic-highchart-example-with-jquery-php-json
The example also shows how to manage multiple series with json.
And tooltips with all series data at mouse point.
You can modify example as per your script requirement.