Chart is not displaying (google charts + codeigniter) - php

I'm trying to display a simple chart but it's not showing on localhost. I'm using codeigniter framework+google charts.
I want to display this simple chart: Chart
Data_model.php:
defined('BASEPATH') OR exit('No direct script access allowed');
class Data_model extends CI_Model {
private $performance = 'sportoviska_zakaznici';
function __construct() {
}
function get_chart_data() {
return $this->db->query('SELECT pohlavie, count(*) as counts FROM sportoviska_zakaznici GROUP BY rok')->result_array();
}
}
Charts.php (controller):
class Charts extends CI_Controller {
function __Construct() {
parent::__Construct();
$this->load->helper(array('form', 'url'));
$this->load->model('data_model', 'chart');
}
public function index()
{
$data['chart_data'] = $this->chart->get_chart_data();
$this->load->view('uvodna_stranka', $data);
}
}
uvodna_stranka.php (view):
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8"/>
<title></title>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js"></script>
<script type="text/javascript">
// Load the Visualization API and the line package.
// google.charts.load('current', {'packages':['bar', 'timeline']});
google.charts.load('current', {'packages':['corechart']});
// Set a callback to run when the Google Visualization API is loaded.
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['pohlavie', 'counts'}],
<?php
foreach ($chart_data as $data) {
echo "['".$data["pohlavie"]."', ".$data["counts"]."],";
}
?>
var options = {
title: 'Company Performance'
};
var chart = new google.visualization.PieChart(document.getElementById('piechart'));
chart.draw(data, options);
}
</script>
</head>
<body>
<b>Bla bla<b>
<div id="piechart" style="width: 900px;"></div>
</body>
</html>
I'm trying to display data from this MySQL table:
Mysql table
When I try to access it from my localhost chart is not being displayed. This is how it looks: Image
So what is the problem?

you can check the browser's console for errors (press F12 on most)
there are a couple issues here...
var data = google.visualization.arrayToDataTable([
['pohlavie', 'counts'}],
<?php
foreach ($chart_data as $data) {
echo "['".$data["pohlavie"]."', ".$data["counts"]."],";
}
?>
first, there is a ending curly brace out of place after --> 'counts'}
remove it...
next, the array for the data doesn't have ending braces --> ]);
change above to...
var data = google.visualization.arrayToDataTable([
['pohlavie', 'counts'],
<?php
foreach ($chart_data as $data) {
echo "['".$data["pohlavie"]."', ".$data["counts"]."],";
}
?>
]);

First you have syntax problems, you have a closing bracket in ['pohlavie', 'counts'}], which doesn't even open or has any porpouse I think.
Then when you have the data, in which you never close the tags from the function:
var data = google.visualization.arrayToDataTable([
['pohlavie', 'counts'}],
<?php
foreach ($chart_data as $data) {
echo "['".$data["pohlavie"]."', ".$data["counts"]."],";
}
I went on https://developers.google.com/chart/interactive/docs/drawing_charts and found out you should probably be using the following first example. In your case it should go along the lines of the following instead of your var data:
data = new google.visualization.DataTable();
data.addColumn('string', 'pohlavie');
data.addColumn('number', 'counts');
data.addRows([
<?php
foreach ($chart_data as $data) {
echo '["'.$data["pohlavie"].'","'.$data["counts"].'"]';
}
?>
]);
Just to be sure you should check the examples of the google charts documentation.

Related

Looking for a way to get data from a google chart into php variable

I have cretae a column chart using Google chart which display a aggregate value. I've add a listener to enable some action when a column is selected.
The listener works as the alert statement displays the element I'd like to use.
How can I save into a php variable the selected item.
I looking for the code to be added in the pp section at the bottom of the display code below .
<div id="chart_div" style="height:400px;width:450px"></div>
<script type="text/javascript">
google.charts.load('current', {'packages':['bar']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
["SousCat_Nom", "Valeur", { role: "style" } ],
<?php
while($row4 = mysqli_fetch_array($resultAll))
{
echo "['".$row4["SousCat_Nom"]."', ".$row4['Valeur']." ,'#4d5ae3'],";
}
?>
]);
var options = {
chart: {
title: 'Dépenses par catégories ',
}
};
var chart = new google.charts.Bar(document.getElementById('chart_div'));
chart.draw(data, google.charts.Bar.convertOptions(options));
chart.draw(data, options);
google.visualization.events.addListener(chart, 'select', selectHandler);
function selectHandler() {
var selectedItem = chart.getSelection()[0,0];
if (selectedItem) {
var value = data.getValue(selectedItem.row, 0);
alert('The user selected ' + value);
<?php
// $data = ?????? ;
?>
}
}
}
</script>

how to set post variable in the sql query to get difference between two dates

I set two variable in date format then i put it in the sql query to find data between two dates and to show them as column chart. But its not working. without script code it shows proper data but when i include script for column it doesn't display any output any suggestion?
Here is the code:
<?php
$user='root';
$pass='';
$db='mypro_bms';
$conn = mysqli_connect('localhost',$user,$pass,$db);
$count=0;
if(isset($_POST['search'])){
$txtStartDate = date('Y-m-d',strtotime($_POST['txtStartDate']));;
$txtEndDate = date('Y-m-d',strtotime($_POST['txtEndDate']));;
$q=mysqli_query($conn,"SELECT blood_group, SUM(blood_bag) as sum FROM donate where date(donation_date)between'$txtStartDate' and '$txtEndDate' group by blood_group");
$count=mysqli_num_rows($q);
}
?>
<html>
<head>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['sum','blood_group'],
<?php
if ($count=="0")
{
echo "No data"; }
else
{
while ($row=$q->fetch_assoc()) {
echo"['".$row['blood_group']."',".$row['sum']."],";
}
}
?>
]);
var options = {
title: 'Blood volume',
is3D: true,
};
var chart = new google.visualization.ColumnChart(document.getElementById('piechart'));
chart.draw(data, options);
}
</script>
</head>

Google Bar Chart from Mysql Database

I have a mysql db with 3 fields region(vachar), new_customers(int) and old_customers(int).
I am trying to create a bar chart with google charts and php but it doesn't work. I think i am doing sth wrong on echo.
Here is my code:
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load('visualization', '1', {packages: ['corechart', 'bar']});
google.setOnLoadCallback(drawMaterial);
function drawMaterial() {
var data = google.visualization.arrayToDataTable([
['Region', 'New Customers', 'Old Customers'],
<?php
$query = "SELECT sum(new_customers) AS new, sum(old_customers) AS old, region FROM daily GROUP BY region";
$exec = mysqli_query($con,$query);
while($row = mysqli_fetch_array($exec)){
echo "['".$row['region']."',";
echo "['".$row['new']."',";
echo "['".$row['old']."',";
}
?>
]);
var options = {
title: 'Country wise new and returned visitors',
bars: 'horizontal'
};
var material = new google.charts.Bar(document.getElementById('barchart'));
material.draw(data, options);
}
</script>
The problem you are having is that the chart is not taking the three parameters in the data variable.
At the moment you have it like: ['Region', 'New Customers', 'Old Customers'],.
Change it to: ['Region', 'New Customers'],.
In the while loop, PHP is not recognising any column with the name $row['new'] or $row['old']. Instead use indexes and change your echo to:
echo "['".$row[2]." [".$row[0]."]', ".$row[1]."],";
I would also recommend you to have the sql query outside the function and have only the iteration through the sql results (the while loop with the echo).
Also, you were not loading the charts properly. You forgot to add the word 'charts':
google.charts.load('visualization', '1', {packages: ['corechart', 'bar']});
google.charts.setOnLoadCallback(drawMaterial);
This is the final solution:
<?php
include("YOUR PHP CONNECT FILE");
$query = "SELECT sum(new_customers) AS new, sum(old_customers) AS old, region FROM daily GROUP BY region";
$exec = mysqli_query($YOURCONNECTIONVARIABLE ,$query);
?>
<!DOCTYPE html>
<head>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.load('visualization', '1', {packages: ['corechart', 'bar']});
google.charts.setOnLoadCallback(drawMaterial);
function drawMaterial() {
var data = google.visualization.arrayToDataTable([
['Region', 'New Customers'],
<?php
while($row = mysqli_fetch_array($exec)){
echo "['".$row[2]." [".$row[0]."]', ".$row[1]."],";
}
?>
]);
var options = {
title: 'Country wise new and returned visitors',
bars: 'horizontal'
};
var material = new google.charts.Bar(document.getElementById('barchart'));
material.draw(data, options);
}
</script>
</head>
<body>
<div id="barchart" style="width: 100%; height: 40em;"></div>
</body>
</html>
Let me know if you have any questions.

$.post into a php class function

I want to make a live username check and I want to use a PHP function.
-->
<?php
require '../../core/init.php';
?>
<!DOCTYPE html>
<html lang="de">
<head>
<meta charset="UTF-8">
<title>KöppCMS - Registrieren</title>
<link rel="stylesheet" href="../../../css/style.css">
<script type="text/javascript" src="../../../js/jquery.js"></script>
<script type="text/javascript" src="../../../js/footer.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#username").keyup(function (e) {
//removes spaces from username
$(this).val($(this).val().replace(/\s/g, ''));
var username = $(this).val(); //get the string typed by user
$.post('users.php', {'username':username}, function(data) { //make ajax call to users.php
$("#user-result").html(data); //dump the data received from PHP page
});
});
});
</script>
</head>
Init.php:
<?php
session_start();
require 'database/connect.php';
require 'classes/users.php';
require 'classes/general.php';
$users = new Users($db);
$general = new General();
$errors = array();
?>
So how can I call the check_username function and send the values to it?
Hope you understand my question, because my English isn't that good.
i'd tried this in the users.php:
<?php
$users = new Users($db);
echo $users->check_username($_POST['username']);
class Users{
private $db;
public function __construct($database) {
$this->db = $database;
}
public function check_username($data) {
return $data+1;
}
function func1($data){
return $data+1;
}
}
Get this Error:
Notice: Undefined variable: db in C:\xampp\htdocs\kcms\system\cms\user\users.php on line 2
Your PHP script should do something like:
<?php
require('init.php'); // This contains $users = new Users($db);
echo $users->check_username($_POST['username']);
For using the return value in your Javascript, see
How do I return the response from an asynchronous call?

PHP code and 2 While calling the same query

I need some help. I have some info in my db that I want to show in 2 charts using Google charts script.
Both scripts works but not when I use both scripts in a same page.. I bet is a problem with the while that are both equals since I need to show the same info. If I delete the first while the second loop start to work, but if no, the first just work.
The app works well because if I hardcode the values by hand and without the while works well both..
Here's the code:
<!-- First Chart start here: -->
<script type="text/javascript">
google.load("visualization", "1", {
packages: ["corechart"]
});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Formato', 'Cantidad'], <? php
//da problema si hay 2 while
while ($DatRDV = mysql_fetch_array($nrollos)) {
echo "['".$DatRDV['Formato'].
"',".$DatRDV['nRollos'].
"],";
} ?> ]);
var options = {
title: 'Formato de Rollos'
};
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
<!-- Second chart start here: -->
<script type="text/javascript">
function drawVisualization() {
// Create and populate the data table.
var JSONObject = {
cols: [{
id: 'format',
label: 'Formato',
type: 'string'
}, {
id: 'cantidad',
label: 'Cantidades',
type: 'number'
}],
rows: [
<? php
while ($DatRDV = mysql_fetch_array($nrollos)) {
echo "{c:[{v: '".$DatRDV['Formato'].
"'}, {v: ".$DatRDV['nRollos'].
"}]},";
} ?> ]
};
var data = new google.visualization.DataTable(JSONObject, 0.5);
// Create and draw the visualization.
visualization = new google.visualization.Table(document.getElementById('table'));
visualization.draw(data, {
'allowHtml': true
});
}
google.setOnLoadCallback(drawVisualization);
</script>
try;
mysql_data_seek($nrollos,0);
before the 2nd loop

Categories