AutoRefrest GoogleChart not work with setinterval() in php javascript - 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>

Related

How to update a Google Chart periodically?

Currently, I'm trying to update the value of my Google Line Chart. My aim is to update it periodically, so that I can obtain the result of a dynamic chart. Right now I need to refresh the whole page, but this is not a good solution.
I tried with setTimeout() function, but recalling the function drawChart() doesn't seem to be working. Here is my JavaScript code:
<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()
{
// The intervals data as narrow lines (useful for showing raw source data)
var options = {
title: 'Valores de LDR1',
vAxis: { ticks: [100, 200, 300, 400, 500, 600, 700, 800, 900, 1000]},
curveType: 'function',
lineWidth: 4,
legend: 'none'
}
var ldr1 = new google.visualization.LineChart(document.getElementById('ldr1'));
var ldr2 = new google.visualization.LineChart(document.getElementById('ldr2'));
var ldr3 = new google.visualization.LineChart(document.getElementById('ldr3'));
var ldr4 = new google.visualization.LineChart(document.getElementById('ldr4'));
var data = google.visualization.arrayToDataTable(<?php prueba('ldr1') ?>);
var data2 = google.visualization.arrayToDataTable(<?php prueba('ldr2') ?>);
var data3 = google.visualization.arrayToDataTable(<?php prueba('ldr3') ?>);
var data4 = google.visualization.arrayToDataTable(<?php prueba('ldr4') ?>);
ldr1.draw(data, options);
options["title"] = "Valores de LDR2";
ldr2.draw(data2, options);
options["title"] = "Valores de LDR3";
ldr3.draw(data3, options);
options["title"] = "Valores de LDR4";
ldr4.draw(data4, options);
updateChart();
setTimeout(drawChart, 1000);
}
The php code get values from the database, so as I see it, I only have to repeat the code of the function drawChart(), but this doesn't happen.

How to get the last row of Google DataTable in 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}]`);

Error: Row given with size different than 5 (the number of columns in the table)

Having a hard time understanding one, presumably, basic thing. Could you please help me out?
I'm trying to create a Line Graph in Google Charts. For some reason it does not let me use NULL values.
First i fetch data via PHP from Postgres:
$rows = pg_fetch_all($fetch);
Then i try to plot the chart:
<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', 'line']});
google.charts.setOnLoadCallback(drawBasic);
function drawBasic() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'X');
data.addColumn('number', 'PD1');
data.addColumn('number', 'CD1');
data.addColumn('number', 'PD2');
data.addColumn('number', 'CD2');
data.addRows([<?php
$result = '';
foreach($rows as $data) {
$result .= "['{$data['m']}', {$data['PD1']}, {$data['CD1']}, {$data['PD2']}, {$data['CD2']}],";
}
$result = rtrim($result,',');
echo $result;
?>])
var options = {
hAxis: {
title: 'T'
},
vAxis: {
title: 'C'
},
interpolateNulls: true,
width: 900,
height: 500,
title: 'Blahblah'
};
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
</head>
<body>
<div id="chart_div"></div>
</body>
</html>
This attempt results in the following error:
jsapi_compiled_default_module.js:97 Uncaught (in promise) Error: Row given with size different than 5 (the number of columns in the table).
at gvjs_P.gvjs_.fZ (jsapi_compiled_default_module.js:97)
at gvjs_P.gvjs_.Op (jsapi_compiled_default_module.js:98)
at drawBasic (view_charts.php:18)
This happens when one of the values in my array is missing, for example:
data.addRows([['00:00', 85, 88, 6, 10],['00:01', 78, 86, 4, 9],['00:02', 110, 64, 8, 8],['00:03', 105, 82, , 4]])
If i change the query to select data where all values are present then the chart is shown without any issues. I thought that it's fine to pass null values, so some parts of the chart would have blank spots? Changing the NULL values to 0 is not an option as the result will be misleading.
Maybe the NULLS should be passed from PHP to JS in some kind of specific way?
Thanks in advance!

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>

Using PHP array in Google Charts

I have an array in my PHP code (budgetingMain.php) called "totals". I want to use it for my data to create a Google Pie Chart. However, I am having difficulty in encoding it.
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
var jsontotals = <?php echo json_encode($totals) ?>;
// Load the Visualization API and the piechart package.
google.load('visualization', '1.0', {'packages':['corechart']});
// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(drawChart);
// Callback that creates and populates a data table,
// instantiates the pie chart, passes in the data and
// draws it.
function drawChart() {
// Create the data table.
var data = new google.visualization.DataTable();
data.addColumn('string', 'Category');
data.addColumn('number', 'Amount Spent on it');
data.addRows([
'jsontotals'
]);
// Set chart options
var options = {'title':'How Much Pizza I Ate Last Night',
'width':400,
'height':300};
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.PieChart(document.getElementById('chartcontainer'));
chart.draw(data, options);
}
</script>
In this current setup, I get the following error: "Uncaught SyntaxError: Unexpected token <" for this line.
var jsontotals = <?php echo json_encode($totals) ?>;
I realise it's an issue with the embedding, but I cannot find a way to get it to work. Any help welcome!
EDIT: This is the structure of totals
$totals = array(
array("ClothingAndAccessories",0),
array("FlowersAndDecorations",0),
array("Ceremony",0),
array("Reception",0),
array("Photography",0),
array("Gifts/favours",0),
array("Stationary",0),
array("Entertainment",0),
array("Other",0)
);

Categories

Resources