How to get the last row of Google DataTable in javascript? - javascript

I have Temperature, Humidity and Time data and can fetch all the values from a database table for use in the DataTable. But I also want to extract the last set of values in the DataTable and print it in console.log.
I tried to print the console.log(data) as shown below and can see all values
<script type="text/javascript">
google.charts.load('current', {'packages':['corechart', 'line']});
google.charts.setOnLoadCallback(drawLineColors);
function drawLineColors() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'time');
data.addColumn('number', 'Temperature');
data.addColumn('number', 'Humidity');
data.addRows([
<?php
if(mysqli_num_rows($result)>0){
while($row = mysqli_fetch_array($result)){
echo "
['".$row['time']."',".$row['temp'].",".$row['hum']."],";
}
}
?>
]);
console.log(data);
var options = {
hAxis: {
title: 'Time'
},
vAxis: {
title: 'Sensors Scale'
},
colors: ['#a52714', '#097138']
};
var chart = new
google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>

You want to use .getValue(rowIndex, columnIndex) (see docs).
This way you can also easily pick and choose what you want, e.g. you might decide you want to use only the temperature, or the humidity values for example, not just the entire row.
let rowIndex = data.getNumberOfRows() - 1; //gets the row index of last row
let lastTime = data.getValue(rowIndex, 0); //gets the first column
let lastTemp = data.getValue(rowIndex, 1); //gets second column
let lastHum = data.getValue(rowIndex,2); //gets third column
console.log(`[${lastTime}, ${lastTemp}, ${lastHum}]`);

Related

AutoRefrest GoogleChart not work with setinterval() in php javascript

I am using the google Chart library to display a chart that I want to update only every second.
As I have the code, it is refreshed because using an alert the alert is shown, but the php query does not refresh me... how can I refresh the chart with the included php query?
My code javascrip, used in php
<script type="text/javascript">
google.charts.load('current', {'packages':['line']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('number', 'D1');
data.addColumn('number', 'D2');
data.addColumn('number', 'D3');
data.addColumn('number', 'V');
data.addRows([
<?
$bus="SELECT * FROM table WHERE Id_test='8574' ORDER BY id DESC LIMIT 15";
$sql=#mysqli_query($con, $bus);
$numer=1;
while($d=#mysqli_fetch_assoc($sql)){
echo '['.$numer.', '.$d[1].', '.$d[2].', '.number_format($d[3],2).'],';
$numer++;
}
?>
]);
var options = {
chart: {
title: 'Title chart',
},
width: 400,
height: 300,
legend: {position: 'none'}
};
var chart = new google.charts.Line(document.getElementById('line_top_x'));
chart.draw(data, google.charts.Line.convertOptions(options));
}
setInterval(drawChart,1000)
Later show in html
<div id="line_top_x"></div>

how to read data from an JSON file and pass it to google chart rows (javascript)

have the following function JSONChart()
it reads json data from var "allText" and should be able to parse the data and use it as row data for google charts.
Commenting out the adding row part displays the column data correctly with empty graph.
Need a way to parse the given sample data from a file and display it as row data in the google chart.
function JSONChart() {
google.charts.load('current', {'packages':['corechart']});
var data = new google.visualization.DataTable();
data.addColumn('string', 'Time stamp');
data.addColumn('number', 'CPU');
data.addColumn('number', 'MEMORY');
data.addColumn({type:'string', role:'annotation'});
data.addColumn({type:'string', role:'annotationText'});
var data1 = JSON.parse(allText);
var dataTableData = google.visualization.arrayToDataTable(data1);
data.addRows (dataTableData);
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
// Set chart options
var options = {'title' : 'CPU & Memory',
hAxis: {
title: 'Time'
},
vAxis: {
title: 'Percentage'
},
'width':1400,
'height':600,
curveType: 'function'
};
chart.draw(data, options);
}
window.onload = function() {
google.charts.setOnLoadCallback(JSONChart());
};
Sample JSON passed into variable "allText"
{"2017/11/03 01:06:51":{"SCREEN":" ABC ","MEMORY":" 32.0142% ","CPU":" 9.1% "},"2017/11/03 02:22:20":{"SCREEN":" XYZ ","MEMORY":" 31.101% ","CPU":" 10.3% "}
a few things...
1) arrayToDataTable expects a simple array, not a json object
it also returns an entire data table, which has already been created --> data
instead, convert each json object to an array,
then use addRows to add the data to the existing data table --> data
something like...
for (var date in data1) {
if (data1.hasOwnProperty(date)) {
chartData.push([
date,
parseFloat(data1[date].MEMORY.replace('%', '').trim()),
parseFloat(data1[date].CPU.replace('%', '').trim()),
data1[date].SCREEN,
'' // not sure what value you want to use here
]);
}
}
data.addRows(chartData);
2) google.charts.load -- this statement waits for the window / document to load, before calling the callback
no need for --> window.onload = function() {...
google.charts.load actually returns a promise,
so you can do something like...
google.charts.load('current', {
packages: ['corechart']
}).then(function () {
// draw chart code here...
3) when passing a callback function to setOnLoadCallback,
a reference to the function should be passed --> JSONChart
not the result of a function --> JSONChart() (remove parens)
4) recommend similar setup as following working snippet...
google.charts.load('current', {
packages: ['corechart']
}).then(function () {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Time stamp');
data.addColumn('number', 'CPU');
data.addColumn('number', 'MEMORY');
data.addColumn({type:'string', role:'annotation'});
data.addColumn({type:'string', role:'annotationText'});
var chartData = [];
var data1 = {"2017/11/03 01:06:51":{"SCREEN":" ABC ","MEMORY":" 32.0142% ","CPU":" 9.1% "},"2017/11/03 02:22:20":{"SCREEN":" XYZ ","MEMORY":" 31.101% ","CPU":" 10.3% "}};
for (var date in data1) {
if (data1.hasOwnProperty(date)) {
chartData.push([
date,
parseFloat(data1[date].MEMORY.replace('%', '').trim()),
parseFloat(data1[date].CPU.replace('%', '').trim()),
data1[date].SCREEN,
'' // not sure what value you want to use here
]);
}
}
data.addRows(chartData);
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
var options = {'title' : 'CPU & Memory',
hAxis: {
title: 'Time'
},
vAxis: {
title: 'Percentage'
},
height: 600,
curveType: 'function'
};
chart.draw(data, options);
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>

JSP x Google Charts X MySQL: Multiple Charts Not Displaying Entire Information

Good morning. I'm trying to make a dynamic web project in Java which connects to a MySQL database to retrieve certain information i need and display it in graphs using Google Charts. In this case, i'm trying to obtain two count values from the table post: number of posts by gender (whether Male or Female) and number of posts by location (whether East or West). Since i'm relatively new to this API, i practiced by displaying a single pie chart with the post count by gender and it works. It displays the number of posts whether the gender is male or female. However, when i try to display two charts (one pie chart with number of posts by gender and one column chart with number of posts by location), they load but they don't show the whole information. Instad of getting the number of posts for both genders and number of posts for both locations, i only get the number of posts for one gender ("Male") and the number of posts for one location ("West").
Here's a picture that illustrates what i'm trying to obtain and what i get instead: https://s31.postimg.org/40c3skgmz/output.jpg
I added some print lines in the JSP code to make sure it retrieves all the information i need and no problem there. However, that's not the case when i pass the data in the HTML.
Here's the JSP code for retrieving the data (using the JSON Library):
<%#page import="java.sql.*" %>
<%#page import="java.util.*" %>
<%#page import="org.json.JSONObject" %>
<%
Connection con= null;
try{
Class.forName("com.mysql.jdbc.Driver").newInstance();
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/sentimentposts?autoReconnect=true&useSSL=false","root","root");
ResultSet rs1 = null;
ResultSet rs2 = null;
List opdetails = new LinkedList();
JSONObject responseObj = new JSONObject();
String query1 = "select poster_gender, count(*) as gender_count from post group by poster_gender";
PreparedStatement pstm1= con.prepareStatement(query1);
String query2 = "select poster_location, count(*) as location_count from post group by poster_location";
PreparedStatement pstm2= con.prepareStatement(query2);
rs1 = pstm1.executeQuery();
rs2 = pstm2.executeQuery();
JSONObject opObj = new JSONObject();
while (rs1.next()) {
String gender = rs1.getString("poster_gender");
System.out.println(gender);
int count = rs1.getInt("gender_count");
System.out.println(count);
opObj.put("gender", gender);
opObj.put("count", count);
}
while(rs2.next()){
String location = rs2.getString("poster_location");
System.out.println(location);
int count2 = rs2.getInt("location_count");
System.out.println(count2);
opObj.put("location", location);
opObj.put("count2", count2);
}
opdetails.add(opObj);
responseObj.put("opdetails", opdetails);
out.print(responseObj.toString());
}
catch(Exception e){
e.printStackTrace();
}finally{
if(con!= null){
try{
con.close();
}catch(Exception e){
e.printStackTrace();
}
}
}
%>
The HTML code that displays the page:
<!DOCTYPE html>
<html>
<head>
<title>Opinion Chart Multi</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization", "1.0", {packages:["corechart", "bar"], callback:drawCharts});
//google.setOnLoadCallback(drawCharts);
var queryObject="";
var queryObjectLen="";
$.ajax({
url : 'getdata.jsp',
dataType:'json',
success : function(data) {
queryObject = eval('(' + JSON.stringify(data) + ')');
queryObjectLen = queryObject.opdetails.length;
},
error : function(xhr, type) {
alert('server error occoured')
}
});
function drawCharts() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'gender');
data.addColumn('number', 'gender_count');
for(var i=0;i<queryObjectLen;i++)
{
var gender = queryObject.opdetails[i].gender;
var count = queryObject.opdetails[i].count;
data.addRows([
[gender,parseInt(count)]
]);
}
var data2 = new google.visualization.DataTable();
data2.addColumn('string', 'location');
data2.addColumn('number', 'location_count');
for(var i=0;i<queryObjectLen;i++)
{
var location = queryObject.opdetails[i].location;
var count2 = queryObject.opdetails[i].count2;
data2.addRows([
[location,parseInt(count2)]
]);
}
var options = {
title: 'Posts By Gender',
};
var options2 = {
title: 'Posts by Location',
colors: ['green','yellow'],
hAxis: {
title: 'Location'
},
vAxis: {
title: 'No. of Posts'
}
};
var chart1 = new google.visualization.PieChart(document.getElementById('chart1'));
chart1.draw(data,options);
var chart2 = new google.visualization.ColumnChart(document.getElementById('chart2'));
chart2.draw(data2,options2);
}
</script>
</head>
<body>
<table class="columns">
<tr>
<td><div id="chart1"></div></td>
<td><div id="chart2"></div></td>
</tr>
</table>
</body>
</html>
And finally, the format of the SQL table i'm using:
Table: post
Columns:
message varchar(45),
poster_age int(11),
poster_gender varchar(45),
poster_location varchar(45)
most likely, drawCharts is being called before the data is ready...
maybe try something like this...
google.load("visualization", "1.0", {
callback: function () {
var queryObject="";
var queryObjectLen="";
$.ajax({
url: 'getdata.jsp',
dataType: 'json',
success: function (data) {
queryObject = eval('(' + JSON.stringify(data) + ')');
queryObjectLen = queryObject.opdetails.length;
var data = new google.visualization.DataTable();
data.addColumn('string', 'gender');
data.addColumn('number', 'gender_count');
for(var i=0;i<queryObjectLen;i++) {
var gender = queryObject.opdetails[i].gender;
var count = queryObject.opdetails[i].count;
data.addRows([
[gender,parseInt(count)]
]);
}
var data2 = new google.visualization.DataTable();
data2.addColumn('string', 'location');
data2.addColumn('number', 'location_count');
for(var i=0;i<queryObjectLen;i++) {
var location = queryObject.opdetails[i].location;
var count2 = queryObject.opdetails[i].count2;
data2.addRows([
[location,parseInt(count2)]
]);
}
var options = {
title: 'Posts By Gender',
};
var options2 = {
title: 'Posts by Location',
colors: ['green','yellow'],
hAxis: {
title: 'Location'
},
vAxis: {
title: 'No. of Posts'
}
};
var chart1 = new google.visualization.PieChart(document.getElementById('chart1'));
chart1.draw(data,options);
var chart2 = new google.visualization.ColumnChart(document.getElementById('chart2'));
chart2.draw(data2,options2);
},
error: function (xhr, type) {
alert('server error occoured')
}
});
},
packages:["corechart"]
});

Google Chart Sorting vs Google Chart Editor

Please help! I am about to go insane over this! I have a Javascript for Google Chart that builds a table and a chart on the same dataset and when you sort the table the values on the chart get sorted as well. I also have a code that opens up the Google Charts Editor... which builds it's own chart. What I need is to merge these two functions. I need to build a table and a chart (that will get sorted as I sort the table) and when I open the Editor I need it to edit THAT chart (which will still be linked with sorting in the table) and NOT build a NEW chart.
Here are the 2 functions I have:
function drawSort() {
var data = new google.visualization.DataTable( <?= $jsonTable ?> );
var formatter = new google.visualization.NumberFormat({
prefix: '$'
});
formatter.format(data, 1); // Apply formatter to second column
var view = new google.visualization.DataView(data);
view.setColumns([0, 1]);
var table = new google.visualization.Table(document.getElementById('table_s_div'));
table.draw(view);
var chart = new google.visualization.BarChart(document.getElementById('chart_s_div'));
chart.draw(view);
google.visualization.events.addListener(table, 'sort',
function (event) {
data.sort([{
column: event.column,
desc: !event.ascending
}]);
chart.draw(view);
});
}
var chartEditor = null;
function loadEditor() {
// Create the chart to edit.
var data = new google.visualization.DataTable( <?= $jsonTable ?> );
var wrapper = new google.visualization.ChartWrapper({
chartType: 'LineChart',
dataTable: data,
options: {
'title': 'Number of Newly Opened Roles per <?echo $_SESSION['
Display ']?>',
'legend': 'none',
}
});
chartEditor = new google.visualization.ChartEditor();
google.visualization.events.addListener(chartEditor, 'ok', redrawChart);
chartEditor.openDialog(wrapper, {})
}
// On "OK" save the chart to a <div> on the page.
function redrawChart() {
chartEditor.getChartWrapper().draw(document.getElementById('chart_s_div'));
}

Google Pie chart usage with Jquery inside a function?

I want to use google pie chart inside jquery and want the chart to be generated based on the condition.
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
var options = {title: 'Sample Chart'};
function drawChart() {
var data1 = new google.visualization.DataTable();
data1.addColumn('string', 'col1');
data1.addColumn('number', 'col2');
data1.addRow(["sample", 12]);
data1.addRow(["sample", 24]);
var chart = new google.visualization.PieChart(document.getElementById('donutchart'));
chart.draw(data1, options);
}
Jquery function,
$.each(result, function(index) {
$("#tableContents").append("some html generation");
});
I want the data1 to be prepared during the loop of Jquery and draw at the end of the function. I see that if I takeout the data1 part of code (shown below) outside the function drawchart, I get
in console log,
Cannot read property 'DataTable' of undefined error
The data1 part of code I removed out of drawChart(),
var data1 = new google.visualization.DataTable();
data1.addColumn('string', 'col1');
data1.addColumn('number', 'col2');
data1.addRow(["sample", 12]);
data1.addRow(["sample", 24]);
Please help, thanks in advance.
You can parse the results into the DataTable like this:
function drawChart() {
var data1 = new google.visualization.DataTable();
data1.addColumn('string', 'col1');
data1.addColumn('number', 'col2');
$.each(result, function(index) {
$("#tableContents").append("some html generation");
// assumes results[index] has "col1Value" and "col2Value" properties
data1.addRow([results[index].col1Value, results[index].col2Value]);
});
var chart = new google.visualization.PieChart(document.getElementById('donutchart'));
chart.draw(data1, options);
}

Categories

Resources