Googlecharts arraytodatatable possible dimension issue? - javascript

I have a 2 arrays which I got from php, put into a single 2D Javascript array. I'm trying to use it to autofill a Google Chart DataTable, but so far I've had no success.
The only thing that I can think of is that maybe the array ix MxN dimension, while the function needs a NxM array?
Either does it not work because the first array is made of numbers?
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>Pressure Monitor</title>
<script type="text/javascript">
var samptable = new Array();
samptable[0] = new Array(2);
samptable[0,0]= nbsamples; //first array obtained from php
samptable[0,1]= samples; //second array obtained from php. both are merged into a 2d array
</script>
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load('visualization', '1', {packages: ['corechart']});
</script>
<script type="text/javascript">
//var data;
function drawVisualization() {
var data = google.visualization.arrayToDataTable(samptable[0]);
// Create and draw the visualization.
new google.visualization.LineChart(document.getElementById('visualization')).
draw(data, {curveType: "function",
width: 500, height: 400,
vAxis: {maxValue: 10}}
);
}
//function draw(){
//}
google.setOnLoadCallback(drawVisualization);
</script>
</head>
<body style="font-family: Arial;border: 0 none;">
<div id="visualization" style="width: 800px; height: 400px;"></div>
</body>
</html>
The code used to get nbsamples and samples:
echo '<script type="text/javascript">';
echo 'var samples = new Array("', join($ydata,'","'), '");';
echo 'var nbsamples = new Array("', join($nbsamples,'","'), '");';
echo '</script>';

Try this instead to create the arrays:
var samptable = [];
samptable.push(nbsamples);
samptable.push(samples);
Then, since it appears that your arrays are all data, make sure to specify *opt_firstRowIsData* option as true (defaults to false):
var data = google.visualization.arrayToDataTable(samptable, true);
You might want to also verify that nbsamples and samples are valid arrays by logging them to the console:
console.log(nbsamples);
console.log(samples);
For this to be valid, they should each appear as a row of data (same number of items), eg:
[5, 4, 10]
[1, 3, 3]

Related

Data from mysql to php to javascript and html for use with chartist

I have a little project going to log temperatures and such to a MySQL database, and I'd like to provide for accessing that info from anywhere.
My initial crude attempt worked pretty well (simply a PHP file getting the MySQL data into an HTML table)
Now I'd like to use some pretty graphs in this project and I've failed despite many many many hours of googling.
Here's the PHP and js/HTML files.
(edit: removed all the mysql stuff to focus on the php->js connection)
this is the php file.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<body>
<?php
$phpvar = ( {labels: ['One', 'Two', 'Three'], series: [[8, 13, 21]] });
$jsvar = json_encode($phpvar);
?>
</body>
</html>
Next, the js/HTML page where I'm trying to pull the data from the PHP script in so that it can be displayed using chartist...
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
<meta content="utf-8" http-equiv="encoding">
<! include chartist>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/chartist.js/latest/chartist.min.css">
<script src="https://cdn.jsdelivr.net/chartist.js/latest/chartist.min.js"></script>
<! include ajax jquery >
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
</head>
<body>
<div class="ct-chart ct-double-octave" id="chart1"></div>
<div id="testdiv">
</div>
<script type="text/javascript">
$.getJSON('stackphp.php', function(data) {
var jsvar = JSON.parse(data);
console.log(jsvar);
var sample= {
labels: ['One', 'Two', 'Three'],
series: [
[8, 13, 21],
[1, 2, 3]
]
}
var chart = new Chartist.Bar('.ct-chart', sample);
</script>
</body>
</html>
#T.Shah... Interestingly, this code does display a sample graph sucessfully...IF if remove the three lines 1 $.getJSON('stackphp.php', function(data) {
var jsvar = JSON.parse(data);
console.log(jsvar);`
Leaveing those three line in however, breaks the whole page... even thought the jsvar variable isn't used in the chartist function. Not sure why that is.
This project is making it clear to me how little I've actually dabbled in web code before. If I can get a fingertip's worth of grip on what I'm missing, I'll pound away at this as much as needed.
Many thanks.
so this project has taught me just tons about javasript, php, and the rest of the webstack.
I’ll try to outline the answer to my original question in case someone else finds this via google.
First, getting data out of mysql using php was pretty easy. Here’s that code…
Setting up a convenient set of variables…
<?php
$hostname = "localhost";
$username = “mysqladminusername”;
$password = “mysqladminpass”;
$db = “tablename”;
$dbconnect=mysqli_connect($hostname,$username,$password,$db);
if ($dbconnect->connect_error) {
die("Database connection failed: " . $dbconnect->connect_error);
}
?>
then pulling the data….
<?php
set_time_limit (60); //needed to prevent timeout error mysql reports the unlimited script takes ~30sec
$query = mysqli_query($dbconnect, "SELECT * FROM tablename ORDER by idcolumnname DESC limit 2000")
or die (mysqli_error($dbconnect));
?>
Then reading the data and putting into an html table…. and creating php arrays with the contents of each mysql column.
<?php
while ($row = mysqli_fetch_assoc($query)) {
echo
"<tr>
<td>{$row[‘col1name’]}</td>
<td>{$row[‘col2name’]}</td>
<td>{$row['col3name’]}</td>
<td>{$row[‘col4name’]}</td>
</tr>\n";
$phpcol1[] = $row[‘col1name’];
$phpcol2[] = $row[‘col2name’];
$phpcol3[] = $row[‘col3name’];
$phpcol4[] = $row[‘col4name’];
}
?>
At this point the php arrays are formatted as normal php “associative arrays”… something like this….
array(10) { [0]=> array(1) { [“col1name”]=> string(3) "658" } [1]=> array(1) { [“col1name”]=> string(3) "657" } [2]=> array(1) { [“col1name”]=> string(3) "658" }
….which is not very useful since chartist doesn’t understand it.
So we need to convert it to the format chartist expects, e.g. [232,345,4545,343,235,32]
(keep in mind that this array is one of two that chartist requires, it needs an array of “labels” and an array of “series”… and then the chartist demo code puts those together and uses them in the final bit of code that actually creates the chartist graph.)
We do this conversion using json encoding.
This can be done in stages, using variables to separate the code for readability, or as a oneliner for compactness.
The compact version is the method I chose in the end.
e.g….
<script type=“text/javascript”>
var jsonlabelsdatavariable = <?php echo json_encode($phpcol1) ?>;
var jsonseriesdatavariable = <?php echo json_encode($phpcol2) ?>;
//comment…here I found it useful to print the formatted array data to the screen so I could see the change with my eyes. To do this, I created an html dviv element like this….
<div class="container" id=“showmethedata”></div>….
in the body of the html page then I put the array data in with the following code…
document.getElementById(“showmethedata”).innerHTML
//comment… while I was testing this, I used placeholder data in the chartist demo code so that I could switch back and forth between the working demo code, and the broken custom code, and use developer tools to see the problems. so below you’ll see that the chartist demo code starts out filled with my placeholder data, then gets emptied out, and then overwritten with the real data from the json variable.
//This is the chartist demo code…..(notice the line feed, I was testing for characters that would break the chartist display, since a problem I had at that time was all the label data being shown in one point of the graph. Turns out this problem was not from bad characters, but that I was pushing my label data into a single label array element.
var data = {
labels: ['2222-02-13_09:12:00','2018-02-13_09:11:00','2018-02-13_09:10:00','2018-02-
13_09:09:00','2018-02-13_09:08:00'],
series: [
[5,2,4,2,0]
]
};
//Now I blank the placeholder arrays…
data.labels.length = 0;
data.series.length = 0;
//now I fill the arrays with the real data…note that two methods are used. this is due to the formatting that chartist expects… the labels array is a single array with elements… while the series array contains an inner array, and that inner array contains the elements. using the push method on the labels array resulted in the labels array being shows as a label for a single data point on the graph.
data.labels = data.labels.concat(jsonlabelsdatavariable);
data.series.push(jsonlight);
//finally we can build the chartist graph…
new Chartist.Line('.ct-chart', data, { width:10000, showArea:true, reverseData: true, });
//and lastly, we close the javascript tag.
</script>
I’ll also note i woulnd up using a few custom functions that edited the contents of my php array elements to do things like remove spaces, add or remove quote marks around each element, etc… but i don’t think any of that was actually necessary.
e.g.
function addquotes ($element){
return "'{$element}'";
}
$withquotes = array_map("addquotes", $sourcearray);
function killspace ($anothersourcearray){
return str_replace(' ' , '_', $anothersourcearray);
}
$phpkillspace = array_map("killspace", $anothersourcearray);
$unspecial = preg_replace("/[^a-zA-Z 0-9]+/", "", $finalsourcearray );
What an adventure.
Cheers!
I was flowing #David 's code and had problems in few spots, so for reference, here is my complete code:
<?php
//here is connection information
require "cont.php";
$db = db_connect();
$upit = "SELECT * FROM (
SELECT * FROM meteo LIMIT 1000
) sub
ORDER BY id ASC";
$rezultat = mysqli_query ($db, $upit);
db_disconnect($db);
$label = array();
$series = array();
if ($rezultat != null)
{
$i = 0;
$j = 0; //vairable for sciping few database enteries.
while($red = mysqli_fetch_assoc($rezultat))
{
$j++;
if ($j == 1)
{
$t = date_create($red['at']);
$label[$i] = date_format($t, 'H:i');
$series[$i] = array($red['dht_temp'], $red['bmx_temp']);
//$series[$i] = array($red['id'], $red['dht_temp'], $red['bmx_temp'], $red['hum'], $red['press'], $red['w_speed'], WindDirectionToString($red['w_dir']));
$i++;
}
// how meny entries to scip
if($j == 10) {
$j = 0;
}
}
}
?>
<!DOCTYPE HTML>
<html>
<head>
<link rel="stylesheet" href="//cdn.jsdelivr.net/chartist.js/latest/chartist.min.css">
<script src="//cdn.jsdelivr.net/chartist.js/latest/chartist.min.js"></script>
</head>
<body>
<div class="ct-chart ct-perfect-fourth"></div>
<script type="text/javascript">
var data = {
labels: <?php echo json_encode($label) ?>,
series: <?php echo json_encode($series); ?>
};
var options = {
width: 1000,
height: 500
};
new Chartist.Line('.ct-chart', data, options);
</script>
</body>
</html>
You need to make sure that '100.php' file return data in the format that chartist expects. If you can make sure of that, then your html file could be like this. Then remove the random data part.
<!DOCTYPE html>
<html>
<head>
<! include chartist>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/chartist.js/latest/chartist.min.css">
<script src="https://cdn.jsdelivr.net/chartist.js/latest/chartist.min.js"></script>
<! include ajax jquery >
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
</head>
<body>
<div class="ct-chart ct-double-octave" id="chart1"></div>
<div id="testdiv">
</div>
<script type="text/javascript">
$.getJSON('100.php', function(data) {
var jsvar = JSON.parse(data);
console.log(jsvar);
// jsvar = {
// // random test data just to build a visible chart
// labels: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri'],
// // random test data just to build a visible chart
// series: [
// [5, 2, 4, 2, 0]
// ]
// };
// Create a new line chart object where as first parameter we pass in a selector
// that is resolving to our chart container element. The Second parameter
// is the actual data object.
new Chartist.Bar('.ct-chart', jsvar);
});
</script>
</body>
</html>

Google chart prints "Table has no columns" in all cases?

I'm trying to generate a line graph with the help of google chart. But, I see "table has no columns". I tried example given on google site and observed the same. Following is my code:
<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 jsonDataString = "{\"cols:\":{\"Time\":\"\",\"Sensor-1\":\"\",\"Sensor-2\":\"\",\"Sensor-3\":\"\",\"Sensor-4\":\"\"},\"rows\":[{\"1\":[{\"Sensor-1\":1024,\"Sensor-2\":1024,\"Sensor-3\":1024,\"Sensor-4\":1024}]},{\"2\":[{\"Sensor-1\":1024,\"Sensor-2\":1024,\"Sensor-3\":1024,\"Sensor-4\":1024}]},{\"3\":[{\"Sensor-1\":1024,\"Sensor-2\":1024,\"Sensor-3\":1024,\"Sensor-4\":1024}]},{\"4\":[{\"Sensor-1\":1024,\"Sensor-2\":1024,\"Sensor-3\":1024,\"Sensor-4\":1024}]},{\"5\":[{\"Sensor-1\":1024,\"Sensor-2\":1024,\"Sensor-3\":1024,\"Sensor-4\":1024}]},{\"6\":[{\"Sensor-1\":1024,\"Sensor-2\":1024,\"Sensor-3\":1024,\"Sensor-4\":1024}]},{\"7\":[{\"Sensor-1\":1024,\"Sensor-2\":1024,\"Sensor-3\":1024,\"Sensor-4\":1024}]},{\"8\":[{\"Sensor-1\":1024,\"Sensor-2\":1024,\"Sensor-3\":1024,\"Sensor-4\":1024}]},{\"9\":[{\"Sensor-1\":1024,\"Sensor-2\":1024,\"Sensor-3\":1024,\"Sensor-4\":1024}]},{\"10\":[{\"Sensor-1\":1024,\"Sensor-2\":1024,\"Sensor-3\":1024,\"Sensor-4\":1024}]}]}";
var jsonData = JSON.parse(jsonDataString);
console.log(jsonData);
var data = new google.visualization.DataTable(jsonData);
var options = {
title: 'time - temp',
curveType: 'function',
legend: { position: 'bottom' }
};
var chart = new google.visualization.LineChart(document.getElementById('curve_chart'));
chart.draw(data, options);
}
</script>
</head>
<body>
<div id="curve_chart" style="width: 900px; height: 500px"></div>
</body>
</html>
Any idea, where am I going wrong?
Thanks.
Your JSON object isn't formatted properly to generate a datatable directly from it. The accepted JSON format is :
{
"cols": [
{"label":"Topping","type":"string"},
{"label":"Slices","type":"number"}
],
"rows": [
{"c":[{"v":"Mushrooms"},{"v":3}]},
{"c":[{"v":"Onions"},{"v":1}]},
{"c":[{"v":"Olives"},{"v":1}]},
{"c":[{"v":"Zucchini"},{"v":1}]},
{"c":[{"v":"Pepperoni"},{"v":2]}
]
}
A nested JSON object with a 'cols' array containing X number of objects, where X = your number of columns, and a 'rows' array, containing Y number of 'c' nodes, where Y = your number of rows, and inside each 'c' node, Z number 'v' nodes, where Z = your number of columns.
You should check google documentation here :
Google JSON DATA
P.S Try replace your JSON string by the one provided in my example and you'll see that your line chart will be drawn as I don't see any errors in your code.

creating google chart from csv using js/jquery

Here is my code to create google chart from csv data. code look fine but still there is some error.
Code looks fine but error is may be due to some jquery syntext. I appreciate if someone can help me
<html>
<head>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js" type="text/javascript"></script>
<script src="http://jquery-csv.googlecode.com/files/jquery.csv-0.71.js"></script>
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
// grab the CSV
$.get("Chart1-data.csv", function(csvString) {
// transform the CSV string into a 2-dimensional array
var arrayData = $.csv.toArrays(csvString, {onParseValue: $.csv.hooks.castToScalar});
alert(arrayData);
// this new DataTable object holds all the data
var data = new google.visualization.arrayToDataTable(arrayData);
// this view can select a subset of the data at a time
var view = new google.visualization.DataView(data);
view.setColumns([0,1]);
// set chart options
var options = {
title: "A Chart from a CSV!",
hAxis: {title: data.getColumnLabel(0), minValue: data.getColumnRange(0).min, maxValue: data.getColumnRange(0).max},
vAxis: {title: data.getColumnLabel(1), minValue: data.getColumnRange(1).min, maxValue: data.getColumnRange(1).max},
legend: 'none'
};
var chart = new google.visualization.PieChart(document.getElementById('piechart'));
chart.draw(data, options);
});
}
</script>
</head>
<body>
<div id="piechart" style="width: 900px; height: 500px;"></div>
</body>
</html>
Chart1-data.csv
Category,
A,34
B,23
C,14
D,57
E,18
Other,5
Error:
SyntaxError: missing ) after argument list
i.e. line where script ends
UPDATE: there was }); missing. Now no error but chart does not appear
Your closing brackets for $.get( should be }); not just };
$.get({
// code
});
And you're also missing a closing curly bracket to close your function.
Demo

How can I put into javascript function on .js file a php value from a php file?

I'm trying to use the Maps API with random coordinates but I don't know and I need some information how can I put into javascript function on .js file a php value from a php file?. For example if we have the several codes:
1) API code to generate a route between 2 coordinates(order2.js):
(function() {
window.onload = function() {
// Creating a map
var options = {
zoom: 8,
center: new google.maps.LatLng(-33.3834, -70.6),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById('map'), options);
// Creating an array that will contain the points for the polyline
var route = [
new google.maps.LatLng(-33.02644,-71.539775),
new google.maps.LatLng(-33.605148,-70.702197)
];
// Creating the polyline object
var polyline = new google.maps.Polyline({
path: route,
strokeColor: "#ff0000",
strokeOpacity: 0.6,
strokeWeight: 5
});
// Adding the polyline to the map
polyline.setMap(map);
};
})();
2) Google Maps Api code to show(map2.html):
<html xmlns="http://www.w3.org/1999/xhtml" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Chapter 4 - Google Maps API 3</title>
<link rel="stylesheet" href="css/graphic.css" type="text/css" media="all" />
<script type="text/javascript"
src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript" src="js/order2.js"></script>
</head>
<body>
<input type="button" value="getValues" id="getValues" />
<input type="button" value="changeValues" id="changeValues" />
<div id="map"></div>
</body>
</html>
3)If I have the next float random code(random.php):
<?php
while($x <= 2995 and $y <= 71333)
{
$x = rand(2025,2995);
$y = rand(70116,71333);
$w = $x/100;
$z = $y/1000;
echo $w."<br>".$z."<br>";
}
?>
Now in basis to before codes I'm really need to know:
How can I to transfer $w and $z values from random.php to any function(a,b) related with order2.js ?
Thanks by your useful help.
Regards
1) if its only for creating random numbers, you can easily do that with javascript.
2) if it's really important to get data from php, the best way is to create a textarea that is hidden from the end user.
in the textarea place all the data you want to transfer to the js files in JSON format!
something like this:
<textarea id="phpData" style="display:none">{"J":5,"test2":"N"}</textarea>
now if you would like to access it from js:
var thePhpData = JSON.parse( $("#phpData").val() );
to get values:
thePhpData.J
thePhpData.test2
The only way is that you have to include your JavaScript into a PHP file...
Order2.php
<?php
include("random.php");
echo "
<script type='text/javascript'>
function(){
...
// to use the values in its place
".$w." .... ".$z."
}
";
</script>
?>
.... are other codes

Google Charts column chart gives Object [object Array] has no method 'getColumnType' when opened

When I open the following HTML document that contains a Google Charts column chart, I get the following error on a blank screen: Object [object Array] has no method 'getColumnType' ... I've tried the suggestions posted on similar questions on this website, but I haven't made any progress. Does anyone know what I'm doing wrong?
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<title>Theme park prices</title>
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load('visualization', '1', {packages: ['corechart']});
</script>
<script type="text/javascript">
google.setOnLoadCallback(function(){
var data = [['Year', 'Disney', 'SeaWorld', 'Universal'], ['2013', 95, 100, 102]];
var options =
{
title:"Theme Park Prices",
width:600,
height:400,
hAxis: {title: "Year"},
};
var chart = new google.visualization.ColumnChart(document.getElementById('priceChart'));
function drawChart()
{
chart.draw(data, options);
}
drawChart();
});
</script>
</head>
<body>
<div id="priceChart" style="width: 600px; height: 400px;margin: 0 auto;"></div>
</body>
</html>
It is an obscure error message that should be fixed. But the solution is simple, it turns out. The chart.draw() method needs a DataTable object, not just an array of arrays. So your data assignment should be like this:
var data = google.visualization.arrayToDataTable(
[['Year', 'Disney', 'SeaWorld', 'Universal'], ['2013', 95, 100, 102]]);

Categories