Google stacked column chart giving an error - php

Hi I am trying for google stacked column charts. But I was getting the following error which I could not able to solve it. The error is "Uncaught TypeError: Cannot read property 'type' of null "
Here my code
<html>
<head>
<title></title>
</head>
<?php $con=mysql_connect("localhost","root", "innernet") or die("Failed to connect with database!!!!");
mysql_select_db("mobiledb", $con);
$user= $_GET['user'];
//echo $user;
$response["cols"] = array();
// $news = array();
//$news["id"] = "";
//$news["label"] = "ID";
//$news["type"] = "string";
//array_push($response["cols"], $news);
array_push($response["cols"], $news);
$news = array();
//$news["id"] = "";
//$news["label"] = "Q9a";
$news["type"] = "number";
array_push($response["cols"], $news);
$news = array();
//$news["id"] = "";
//$news["label"] = "Q9b";
$news["type"] = "number";
array_push($response["cols"], $news);
// $news = array();
// $news["id"] = "";
//$news["label"] = "ts";
// $news["type"] = "number";
// array_push($response["cols"], $news);
$result = mysql_query("SELECT `Q9a`, `Q9b` FROM goaltest WHERE id='$user'") or die(mysql_error());
if (mysql_num_rows($result) > 0)
{
$response["rows"] = array(); $table = array(); $rows = array();
while ($row = mysql_fetch_array($result))
{
$temp = array();
//$temp[] = array('v' => (string) $row['id']);
$temp[] = array('v' => (int) $row['Q9a']);
$temp[] = array('v' => (int) $row['Q9b']);
//$temp[] = array('v' => (int) $row['ts']);
array_push($response["rows"], array('c' => $temp));
}
//echo json_encode($response);
}
?>
<!--Load the AJAX API -->
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
google.load("visualization", "1.0", {packages:["imagechart"]});
</script>
<script type='text/javascript'>
google.setOnLoadCallback(drawChart);
function drawChart() {
var response = '<?php echo json_encode($response); ?>'; alert(' hi ' + response);
var obj = eval ("(" + response + ")");
var dataTable = new google.visualization.DataTable(response);
var options = {cht: 'bvs', chs: '300x125', colors:['#4D89F9','#C6D9FD'],
chds:'0,160', chxl:'0:|oranges|apples|pears|bananas|kiwis|'};
var chart = new google.visualization.ImageChart(document.getElementById('bar_div'));
chart.draw(dataTable, options);
}
</script>
<body>
<div id='bar_div'></div>
</body>
</html>
So please any one tell me how to solve this
<html>
<head>
<title></title>
</head>
<!--Load the AJAX API -->
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
google.load("visualization", "1.0", {packages:["imagechart"]});
</script>
<script type='text/javascript'>
google.setOnLoadCallback(drawChart);
function drawChart() {
var response = '{"cols":[null,{"type":"number"},{"type":"number"}],"rows":[{"c":[{"v":12},{"v":23}]},{"c":[{"v":37},{"v":55}]}]}'; alert(' hi ' + response);
var obj = eval ("(" + response + ")");
var dataTable = new google.visualization.DataTable(response);
var options = {cht: 'bvs', chs: '300x125', colors:['#4D89F9','#C6D9FD'],
chds:'0,160', chxl:'0:|oranges|apples|pears|bananas|kiwis|'};
var chart = new google.visualization.ImageChart(document.getElementById('bar_div'));
chart.draw(dataTable, options);
}
</script>
<body>
<div id='bar_div'></div>
</body>
</html>

(#asgallant has probably guessed right already.) In your first array_push(... $news) The $news is not yet defined. Consequently, the first array element under the "cols" property in the response variable is null. Maybe you just want to comment out that first array_push.

Related

convert data from mysql db to table using an json/php api

I'm trying to make my own api using a JSON and PHP script, which is successfully working (api.mystem.tk/product), however I want to convert that data to an html table with the columns: id, name and date.
My question, how? I've got my code included and you can watch the JSON output in the console of api.mystem.tk/product. I've deleted all the private details in the scripts and replaced them with #______.
api.php:
<?php
$connect = mysqli_connect('#host', '#user', '#password', '#db');
if(!isset($_GET['function'])) {
die('Some error occurred!');
}
function GetProducts($db) {
$sql = mysqli_query($db, 'SELECT * FROM php_test ORDER BY Id ASC LIMIT
0, 10');
$data = array();
if (mysqli_num_rows($sql) > 0) {
while ($row = mysqli_fetch_array($sql)) {
$data[] = $row["Id"];
$data[] = $row["Name"];
$data[] = $row["Date"];
}
}
$data = json_encode($data);
echo $_GET['jsonCallback'].'('.$data.')';
}
if (function_exists($_GET['function'])) {
$_GET['function']($connect);
}
echo $data;
?>
function.js:
$(function(){
var functionName = 'GetProducts';
function LoadData() {
$.getJSON("http://api.mystem.tk/product/api.php?
function="+functionName+"&jsonCallback=?", function(data) {
var all_data = [];
$.each(data, function(k, name){
var array_data = '<div class="names">'+name+'</div>';
all_data.push(array_data);
});
$('#data').append(all_data);
console.log(data);
});
}
LoadData();
});
index.php:
<!DOCTYPE html>
<html lang="en">
<head>
<title> API TEST </title>
<meta name="viewport" content="width=device-width,initial-
scale=1,maximum-scale=1,user-scalable=0">
<script src="https://code.jquery.com/jquery-3.3.1.min.js"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous"></script>
</head>
<body>
<div id="data"></div>
<script type="text/javascript" src="function.js"></script>
</body>
</html>
so i've tried using $.parseJSON instead of $getJSON, but without succes
console:
Uncaught SyntaxError: Unexpected token <
at m (jquery-3.3.1.min.js:2)
at Function.globalEval (jquery-3.3.1.min.js:2)
at text script (jquery-3.3.1.min.js:2)
at Ut (jquery-3.3.1.min.js:2)
at k (jquery-3.3.1.min.js:2)
at XMLHttpRequest.<anonymous> (jquery-3.3.1.min.js:2)
and i've changed this:
$data[] = $row["Id"];
$data[] = $row["Name"];
$data[] = $row["Date"];
to this:
$data[] = array(
'id' => $row["Id"],
'name'=> $row["Name"],
'date'=> $row["Date"]
)
to be a little bit more specified...
You'll need to parse JSON data in your function.js using jQuery.parseJSON() jQuery function.
You can read brief documentation from: jQuery.parseJSON()
Added code:
<script>
var obj = JSON.stringify([
{
"id":'1',
"name":'Jhon Doe',
"date":'April 14,2018'
},
{
"id":'2',
"name":'Coder',
"date":'April 23, 2018'
}
]);
var jsontoparse = JSON.parse(obj);
var i = obj.length;
var j=0;
while(j<=i){
console.log(jsontoparse[j].id);
j = j+1;
}
</script>

Issues displaying Google Charts graph when connecting to database

I'm trying to get Google Charts to display a graph of what I have in my MySQL database. Unfortunately, it's not displaying anything. I know there has to be some sort of small error that I'm missing.
<?php
mysql_connect("Localhpst", "Username", "password");
mysql_select_db("DBName") or die(mysql_error());
$sth=mysql_query("SELECT *
FROM Graph")
or die(mysql_error());
$rows = array();
$flag = true;
$table = array();
$table['cols'] = array(
array('label' => 'people', 'type' => 'string'),
array('label' => 'total', 'type' => 'number')
);
$rows = array();
while($r = mysql_fetch_assoc($sth)) {
$temp = array();
$temp[] = array('v' => (string) $r['people']);
$temp[] = array('v' => (int) $r['total']);
$rows[] = array('c' => $temp);
}
$table['rows'] = $rows;
$jsonTable = json_encode($table);
//echo $jsonTable;
?>
<html>
<head>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script type="text/javascript">
// Load the Visualization API and the piechart package.
google.load('visualization', '1', {'packages':['corechart']});
// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(drawChart);
function drawChart() {
// Create our data table out of JSON data loaded from server.
var data = new google.visualization.DataTable(<?=$jsonTable?>);
var options = {
title: ' Something ',
is3D: 'true',
width: 800,
height: 600
};
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
</head>
<body>
<!--this is the div that will hold the pie chart-->
<div id="chart_div"></div>
</body>
</html>
What is missing that would result in this displaying nothing on the screen. The only thing it displays is the "Something" from the title. I know there is data in the database, so that's not the issue. I'm also fairly certain it's not a connection issue, so I'm stumped.

JSON PHP Google Visualisation

Trying to get my json output in the right format for a google visualisation line chart but I am clearly doing something wrong as it is returning table has no columns. As explained in the docs I am using Ajax to call a php page.
getData.php
<?php
class MyDB extends SQLite3
{
function __construct()
{
$this->open('water.db');
}
}
$db = new MyDB();
if(!$db){
echo $db->lastErrorMsg();
} else {
//echo "Opened database successfully\n";
}
$sql =<<<EOF
SELECT * from wT;
EOF;
$data = array();
$data['cols'][] = array('label' => 'Temperature', 'type' => 'number');
$data['cols'][] = array('label' => 'Time', 'type' => 'string');
$rows = array();
$ret = $db->query($sql);
while($row = $ret->fetchArray(SQLITE3_ASSOC) ){
$temp = array();
$temp[] = array('v' => (float) $row['fishTemp']);
$temp[] = array('v' => (string) $row['time']);
$rows = array('c' => $temp);
$data['rows'][] = $rows;
}
$jsonTable = json_encode($data, true);
var_dump($jsonTable);
$db->close();
?>
base.html
<html>
<head>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var jsonData = $.ajax({
url: "getData.php",
dataType:"json",
async: false
}).responseText;
// Create our data table out of JSON data loaded from server.
console.log(jsonData);
//var obj = window.JSON.stringify(jsonData);
var data = new google.visualization.DataTable(jsonData);
var options = {
title: 'Title'
};
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
</head>
<body>
<div id="chart_div" style="width: 900px; height: 500px;"></div>
</body>
</html>
The output from the console looks like this....what am I missing?!
"{"cols":[{"label":"Temperature","type":"string"},{"label":"Time","type":"date"}],"rows":[{"c":[{"v":18.25},{"v":"2014-08-19 16:23:23"}]},{"c":[{"v":18.25},{"v":"2014-08-19 16:23:31"}]},{"c":[{"v":18.25},{"v":"2014-08-19 16:23:39"}]},{"c":[{"v":18.25},{"v":"2014-08-19 16:23:47"}]},{"c":[{"v":18.25},{"v":"2014-08-19 16:23:55"}]},{"c":[{"v":18.25},{"v":"2014-08-19 16:24:06"}]},{"c":[{"v":18.25},{"v":"2014-08-19 16:24:14"}]}
Loading dataTable with json accepts dates as a string in the following format: Date(year, month, day[,hour, minute, second[, millisecond]]) where everything after day is optional, and months are zero-based.
So for your first timeStamp, it should be :
{"v":"Date(2014,07,19,16,23,23)"}
If you want to use directly the milliseconds time:
{"v":"Date(1411154603000)}

Echo PHP value inside a jquery Function

I am trying to assign a php echo value to an input generated from a jquery function. But so far no luck. It breaks the function and no results are displayed along with the input field. What is the proper way for this scenario to display php value inside the query function.
PHP
$tablename = "table";
$next_increment = 0;
//$qShowStatus = "SHOW TABLE STATUS LIKE '$tablename'";
$qShowStatusResult = $db_con->prepare("SHOW TABLE STATUS LIKE '$tablename'");
$qShowStatusResult->execute();
$results = $qShowStatusResult->fetchAll(\PDO::FETCH_ASSOC);
foreach($results as $value){
$next_increment = $value['Auto_increment'];
}
var nextAutoIncrement = '"'<?php echo $next_increment; ?>'"';
Jquery
newSection.children(':nth-child(1)').children(':first').attr('id', 'auto_id_' + newNum).attr('name', 'auto_id_' + newNum).val(nextAutoIncrement).hide();
Try this
<script language="javascript" type="text/javascript">
var nextAutoIncrement = '<?php echo $next_increment;?>';
</script>
Try like this:
<script language="javascript" type="text/javascript"
var nextAutoIncrement = <?php echo $next_increment; ?>;
</script>
<script>
//if it is anumber
var nextAutoIncrement = <?php echo $next_increment; ?>;
// if ity is a string
var nextAutoIncrement = '<?php echo $next_increment;?>';
</script>
In JS code there is require to define the <script> tag:
$tablename = "table";
$next_increment = 0;
$qShowStatusResult = $db_con->prepare("SHOW TABLE STATUS LIKE '$tablename'");
$qShowStatusResult->execute();
$results = $qShowStatusResult->fetchAll(\PDO::FETCH_ASSOC);
foreach($results as $value){
$next_increment = $value['Auto_increment'];
}
<script type="text/javascript" >
var nextAutoIncrement = '<?php echo $next_increment; ?>';
</script>

Google Visualization Column Chart - How to make labels as currency

I'm just trying to figure out to format my labels to be shown as a currency and not just a number:
echo ' <script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn("string", "ZipCode");
data.addColumn("number", "Sales");
data.addRows('.$count.');';
$i = 0;
foreach ($results as $r) {
$p = (($r->report_trans_amount / $total) * 100);
$pd = strval(number_format($p, 1));
echo ' data.setValue(' . $i . ', 0, "' . $r->member_address_zip_code .
' - ' . $pd . '%");';
echo ' data.setValue(' . $i . ', 1, ' . $r->report_trans_amount . ');';
$i++;
}
echo ' var chart = new google.visualization.PieChart(
document.getElementById("chart_div"));
chart.draw(data, {width:900, height:500, is3D:true});
}
</script>
<div id="chart_div"></div>
';
I would like the Sales column to be shown as a USD currency value. How can I do that? I see how to do it using the URL request, but that does not help this situation.
I just can't seem to find any good example on this.
it looks like you might want to look at setFormattedValue
http://code.google.com/apis/chart/interactive/docs/reference.html#DataTable_setFormattedValue
and for the format stuff look at
http://code.google.com/apis/chart/interactive/docs/reference.html#formatters
I haven't tried this out, but from what I can tell this could work for you:
echo '
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn("string", "ZipCode");
data.addColumn("number", "Sales");
data.addRows('.$count.');
var formatter = new google.visualization.NumberFormat({prefix: \'$\'});
formatter.format(data, 1);';
$i = 0;
foreach($results as $r){
$p = (($r->report_trans_amount / $total) * 100);
$pd = strval(number_format($p, 1));
echo 'data.setValue('.$i.', 0, "'.$r->member_address_zip_code.' - '.$pd.'%");';
//echo 'data.setFormattedValue('.$i.', 1, formatter);'; // might not need this with the formatter.format above
echo 'data.setValue('.$i.', 1, '.$r->report_trans_amount.');';
$i++;
}
echo ' var chart = new google.visualization.PieChart(document.getElementById("chart_div"));
chart.draw(data, {width:900, height:500, is3D:true});
}
</script>
<div id="chart_div"></div>
';
references:
http://code.google.com/p/google-visualization-api-issues/issues/detail?id=282

Categories