Google Charts with PHP and javascript arrays - javascript

I am trying to loop through an array elements to populate a google chart. I can call array elements directly in php and in javascript and I also even converted a php array into a javascript array. But I can only call an array element and not loop through an array.
What I can do...
<script src="js/modernizr.js"></script>
<!--Load the AJAX API-->
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
var dateArray = <?php echo (json_encode($arrayDate)); ?>;
var hitsArray = <?php echo (json_encode($arrayHits)); ?>;
<!---document.write(myVariable);-->
<!--Content Delivery Network Stats-->
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Date', 'Hits'],
[dateArray[0], +hitsArray[0] ],
[dateArray[1], +hitsArray[1] ],
[dateArray[2], +hitsArray[2] ]
]);
var options = { title: 'Content Delivery Network Stats',
hAxis: {title: 'Date', titleTextStyle: {color: 'red'}} };
var chart = new google.visualization.ColumnChart (document.getElementById('chart_div')); chart.draw(data, options); }
<!--Content Delivery Network Stats-->
</script>
What I am trying to do....
<script src="js/modernizr.js"></script>
<!--Load the AJAX API-->
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
var dateArray = <?php echo (json_encode($arrayDate)); ?>;
var hitsArray = <?php echo (json_encode($arrayHits)); ?>;
<!---document.write(myVariable);-->
<!--Content Delivery Network Stats-->
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var myDataArray = [['Date', 'Hits']];
for (var i = 0; i < dateArray.length; i++) {
myDataArray.push([dateArray[i], hitsArray[i]);
}
var data = google.visualization.arrayToDataTable(myDataArray);
var options = { title: 'Content Delivery Network Stats',
hAxis: {title: 'Date', titleTextStyle: {color: 'red'}} };
var chart = new google.visualization.ColumnChart(document.getElementById('chart_div')); chart.draw(data, options); }
<!--Content Delivery Network Stats-->
</script>

Try this:
var myDataArray = [['Date', 'Hits']];
for (var i = 0; i < dateArray.length; i++) {
myDataArray.push([dateArray[i], hitsArray[i]]);
}
var data = google.visualization.arrayToDataTable(myDataArray);

Related

How to draw line chart from Two variables in two different MySQL tables

I am new in php and learing how to draw Line chart for two different Temperature values in two different tables in MySQL. I can fetch the data from one table and draw it in a chart but I couldn't figured it out how to fetch the two temprature values from two different tables.
First table1:
id temp
1 20
Second Table2:
id temp
1 25
data.php code:
<?php
$servername = "localhost";
$database = "test";
$username = "test";
$password = "12345";
$connect = mysqli_connect($servername, $username, $password, $database);
if (!$connect) {
die("Connection failed: " . mysqli_connect_error());
}
$query = ("SELECT * FROM Table1 UNION SELECT * FROM Table2");
$result = mysqli_query($connect, $query);
$data = array();
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
array_push($data, [$row['time'], floatval($row['temp']), $row['time'], floatval($row['temp'])]);
}
}
echo json_encode($data);
mysqli_close($connect);
?>
the JS code :
setInterval(function () {
google.charts.load('current', {'packages':['corechart', 'line']});
google.charts.setOnLoadCallback(drawLineColors);
function drawLineColors() {
var data = new google.visualization.DataTable(jsonData);
data.addColumn('string', 'Date');
data.addColumn('number', 'Temperature');
data.addColumn('string', 'Date');
data.addColumn('number', 'Temperature2');
var jsonData = $.ajax({
url: "data.php",
dataType: "json",
async: false
}).responseText;
var obj = JSON.parse(jsonData);
data.addRows(obj);
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 rowIndex2 = data.getNumberOfRows() - 1; //gets the row index of last row
let lastTime2 = data.getValue(rowIndex, 0); //gets the first column
let lastTemp2 = data.getValue(rowIndex,1); //gets third column
console.log(` ${lastTemp}, ${lastTemp2}`);
$(".TempStatus").html(lastTemp + " °C");
$(".Temp2Status").html(lastTemp2 + " °C");
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, google.charts.Line.convertOptions(options));
}
}, 5000);
How can I fetch the two temperature values from two tables?
first, let's query both tables separately.
then combine the data for the response, Table1 & Table2...
<?php
$servername = "localhost";
$database = "test";
$username = "test";
$password = "12345";
$connect = mysqli_connect($servername, $username, $password, $database);
if (!$connect) {
die("Connection failed: " . mysqli_connect_error());
}
$data = array(
'Table1' => array(),
'Table2' => array()
);
$query = ("SELECT * FROM Table1");
$result = mysqli_query($connect, $query);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
array_push($data['Table1'], [$row['time'], floatval($row['temp'])]);
}
}
$query = ("SELECT * FROM Table2");
$result = mysqli_query($connect, $query);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
array_push($data['Table2'], [$row['time'], floatval($row['temp'])]);
}
}
echo json_encode($data);
mysqli_close($connect);
?>
when drawing the chart, we can only have one x-axis.
so we will need to join the two tables on the time column.
but first, google charts only needs to be loaded once.
not every time we draw the chart.
so we'll load google charts first, before anything else.
and we don't know exactly how long it will take to get the data and draw the chart.
instead of using setInterval, we'll use setTimeout after the first draw has finished.
google.charts.load('current', {
packages: ['corechart']
}).then(function () {
var options = {
hAxis: {
title: 'Time'
},
vAxis: {
title: 'Sensors Scale'
},
colors: ['#a52714', '#097138']
};
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
google.visualization.events.addListener(chart, 'ready', function () {
setTimeout(drawLineColors, 5000);
});
drawLineColors();
function drawLineColors() {
var data1 = new google.visualization.DataTable();
data1.addColumn('string', 'Date');
data1.addColumn('number', 'Temperature');
var data2 = new google.visualization.DataTable();
data2.addColumn('string', 'Date');
data2.addColumn('number', 'Temperature');
$.ajax({
url: 'data.php',
dataType: 'json',
}).done(function (jsonData) {
data1.addRows(jsonData.Table1);
data2.addRows(jsonData.Table2);
var joinData = google.visualization.data.join(data1, data2, 'full', [[0, 0]], [1], [1]);
var rowIndex = data1.getNumberOfRows() - 1;
var lastTime = data1.getValue(rowIndex, 0);
var lastTemp = data1.getValue(rowIndex, 1);
var rowIndex2 = data2.getNumberOfRows() - 1;
var lastTime2 = data2.getValue(rowIndex2, 0);
var lastTemp2 = data2.getValue(rowIndex2, 1);
$(".TempStatus").html(lastTemp + " °C");
$(".Temp2Status").html(lastTemp2 + " °C");
chart.draw(joinData, options);
});
}
});
other notes...
async: false on ajax has been deprecated, use the done callback instead.
don't need the 'line' package in google charts, it is for material line charts.
you're using a classic line chart --> google.visualization.LineChart
material --> google.charts.Line
as well, don't need to convert the options for a classic chart,
removed --> google.charts.Line.convertOptions

How to set export csv option to button in google visualization Pie chart

I am using Google visualization pie chart for showing transaction state.
I want to export to csv, there is functionality ToolBar to export csv,html,iGoogle but I want to specific to csv only without select options.
you can use static method --> dataTableToCsv
google.visualization.dataTableToCsv
this will create a csv string of the data in a data table.
it will not export the column headings, but those can be added manually...
see following working snippet...
google.charts.load('current', {
packages: ['corechart']
}).then(function () {
var data = google.visualization.arrayToDataTable([
['Label', 'Value'],
['A', 10],
['B', 20],
['C', 30],
['D', 40],
['E', 50],
['F', 60]
]);
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(data);
$('.csv-button').on('click', function () {
var browserIsIE;
var csvColumns;
var csvContent;
var downloadLink;
var fileName;
// build column headings
csvColumns = '';
for (var i = 0; i < data.getNumberOfColumns(); i++) {
csvColumns += data.getColumnLabel(i);
if (i < (data.getNumberOfColumns() - 1)) {
csvColumns += ',';
}
}
csvColumns += '\n';
// build data rows
csvContent = csvColumns + google.visualization.dataTableToCsv(data);
// download file
browserIsIE = false || !!document.documentMode;
fileName = 'data.csv';
if (browserIsIE) {
window.navigator.msSaveBlob(new Blob([csvContent], {type: 'data:text/csv'}), fileName);
} else {
downloadLink = document.createElement('a');
downloadLink.href = 'data:text/csv;charset=utf-8,' + encodeURI(csvContent);
downloadLink.download = fileName;
raiseEvent(downloadLink, 'click');
downloadLink = null;
}
});
function raiseEvent(element, eventType) {
var eventRaised;
if (document.createEvent) {
eventRaised = document.createEvent('MouseEvents');
eventRaised.initEvent(eventType, true, false);
element.dispatchEvent(eventRaised);
} else if (document.createEventObject) {
eventRaised = document.createEventObject();
element.fireEvent('on' + eventType, eventRaised);
}
}
});
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script src="https://www.gstatic.com/charts/loader.js"></script>
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css">
<div>
<button class="csv-button ui-button ui-widget ui-corner-all">
<span class="ui-icon ui-icon-circle-triangle-s"></span><span> Download CSV</span>
</button>
</div>
<div id="chart_div"></div>
Google will provide you u need to pass your API key inside it
<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']});
var visualization;
function draw() {
drawVisualization();
drawToolbar();
}
function drawVisualization() {
var container = document.getElementById('visualization_div');
visualization = new google.visualization.PieChart(container);
new google.visualization.Query('https://spreadsheets.google.com/tq?key=pCQbetd-CptHnwJEfo8tALA').
send(queryCallback);
}
function queryCallback(response) {
visualization.draw(response.getDataTable(), {is3D: true});
}
function drawToolbar() {
var components = [{type: 'csv', datasource: 'https://spreadsheets.google.com/tq?key=pCQbetd-CptHnwJEfo8tALA'},
];
var container = document.getElementById('toolbar_div');
google.visualization.drawToolbar(container, components);
};
google.charts.setOnLoadCallback(draw);
</script>
</head>
<body>
<div id="visualization_div" style="width: 270px; height: 200px;"></div>
<div id="toolbar_div"></div>
</body>
</html>
fore more :
https://developers.google.com/chart/interactive/docs/gallery/toolbar

Unable to draw a google chart from firebase db

I want to visualize some simple sensor readings stored in firebase in a basic line graph from Google charts.
The data is structured like this:
KgPdzr3PgDaKVa73asd: {
date: "29/03/201
time: "15:21:07"
value: 21.461541056632996
}
Unfortunately the line graph won't load, and I can't figure out why. The json objects is loaded successfully, so I think it's got something to do with the drawing part of it. Any help in the right direction will be most appreciated.
<script src="https://www.gstatic.com/firebasejs/3.7.4/firebase.js"></script>
<script src=" http://www.google.com/uds/modules/gviz/gviz-api.js"></script>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
// Initialize Firebase
var config = {
apiKey: "AIzaSyBGiHpuzcgw_Ettlko_oU66U-gbW_SbEUA",
authDomain: "internet-of-things-62d39.firebaseapp.com",
databaseURL: "https://internet-of-things-62d39.firebaseio.com",
projectId: "internet-of-things-62d39",
storageBucket: "internet-of-things-62d39.appspot.com",
messagingSenderId: "143567304866"
};
firebase.initializeApp(config);
var database = firebase.database();
firebase.database().ref('/Oslo/temperature').once('value').then(function(snapshot) {
temps = snapshot.val();
console.log(temps);
google.charts.load('current', {'packages':['corechart','line']});
google.charts.setOnLoadCallback(drawChart(temps));
});
function parse (temp){
return(new Date(temp.replace(/-/g, '/'))).getTime()
}
// google.charts.load('current', {'packages':['corechart', 'line']});
// google.charts.setOnLoadCallback(drawChart);
function drawChart(temps) {
var array = $.map(temps, function(value, index) {
return [value];
});
var data = new google.visualization.DataTable();
data.addColumn('number', 'date');
data.addColumn('number', 'time');
data.addColumn('number', 'value');
var sort = function(a,b){return parse (a.time) - parse(b.time)};
var tempData = array.sort(sort);
var output=[];
for (var i = 0; i<tempData.length;i++){
var item = tempData[i];
output.push([
// parseFloat(parse(item.time)),
parseFloat(item.time),
parseFloat(item.date),
parseFloat(item.value)
]);
}
console.log(output);
data.addRows(output);
var options = {
chart: {
title: 'title',
subtitle: 'subtitle'
},
width: 900,
height: 500
};
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
<div id="chart_div"></div>
Added (bold): 'https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js'
Made some minor changes as well. Cheers. Removed some errors by changing jquery version which is loaded.
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://www.gstatic.com/firebasejs/3.7.4/firebase.js"></script>
<script src=" http://www.google.com/uds/modules/gviz/gviz-api.js"></script>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
// Initialize Firebase
var config = {
apiKey: "AIzaSyBGiHpuzcgw_Ettlko_oU66U-gbW_SbEUA",
authDomain: "internet-of-things-62d39.firebaseapp.com",
databaseURL: "https://internet-of-things-62d39.firebaseio.com",
projectId: "internet-of-things-62d39",
storageBucket: "internet-of-things-62d39.appspot.com",
messagingSenderId: "143567304866"
};
firebase.initializeApp(config);
var database = firebase.database();
firebase.database().ref('/Oslo/temperature').once('value').then(function(snapshot) {
temps = snapshot.val();
console.log(temps);
google.charts.load('current', {
'packages': ['corechart', 'line']
});
google.charts.setOnLoadCallback(drawChart(temps));
});
function parse(temp) {
return (new Date(temp.replace(/-/g, '/'))).getTime()
}
function drawChart(temps) {
var array = $.map(temps, function(value, index) {
return [value];
});
var data = new google.visualization.DataTable();
data.addColumn('number', 'date');
data.addColumn('number', 'time');
data.addColumn('number', 'value');
var sort = function(a, b) {
return parse(a.time) - parse(b.time)
};
var tempData = array.sort(sort);
var output = [];
for (var i = 0; i < tempData.length; i++) {
var item = tempData[i];
output.push([
// parseFloat(parse(item.time)),
parseFloat(item.time),
parseFloat(item.date),
parseFloat(item.value)
]);
}
console.log(output);
data.addRows(output);
var options = {
chart: {
title: 'title',
subtitle: 'subtitle'
},
width: 900,
height: 500
};
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
console.log("data + options: " + data, options)
chart.draw(data, options);
}
google.charts.load('current', {
'packages': ['corechart', 'line']
});
google.charts.setOnLoadCallback(drawChart);
</script>

Organization Chart from sharepoint list items

I want to create an organization chart which I want to populate using the values from a sharepoint list. I would like to retrieve items using REST and Javascript. Here is my code. It in partially working, but cannot create a chart. Please help someone.
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization", "1", { packages: ["orgchart"] });
google.setOnLoadCallback(drawChart);
function drawChart() {
debugger;
$.ajax({
url: "http://myurl/_api/Web/Lists/GetByTitle('Employee Hierarchy')/items",
type: "GET",
headers: {
"accept": "application/json;odata=verbose",
},
success: function (r) {
debugger;
var items = r.d.results;
var data = new google.visualization.DataTable();
data.addColumn('string', 'Entity');
data.addColumn('string', 'ParentEntity');
data.addColumn('string', 'ToolTip');
for (var i = 0; i <items.length; i++) {
var employeeId = r.d[i][0].toString();
var employeeName = r.d[i][1];
var designation = r.d[i][2];
var reportingManager = r.d[i][3] != null ? r.d[i][3].toString() : '';
data.addRows([[{
v: employeeId,
f: employeeName + '<div>(<span>' + designation + '</span>)</div><img src = "Pictures/' + employeeId + '.jpg" />'
}, reportingManager, designation]]);
var chart = new google.visualization.OrgChart($("#chart")[0]);
chart.draw(data, { allowHtml: true });
},
failure: function (r) {
alert(r.d);
},
error: function (r) {
alert(r.d);
}
});
}
</script>
<div id="chart">
</div>
this is the structure of my sharepoint list
The following example demonstrates how to visualize SharePoint List data as organization chart via Google Visualization API
google.load("visualization", "1", { packages: ["orgchart"] });
google.setOnLoadCallback(displayChart);
function displayChart()
{
loadListItems('Employee Hierarchy')
.done(function(data){
var items = data.d.results;
drawChart(items);
})
.fail(function(error){
console.log(error);
});
}
function drawChart(items) {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Name');
data.addColumn('string', 'Manager');
data.addColumn('string', 'ToolTip');
for (var i = 0; i < items.length; i++) {
data.addRow([items[i]['Title'],items[i]['Manager']['Title'],'']);
}
var chart = new google.visualization.OrgChart(document.getElementById('chart_div'));
chart.draw(data, { allowHtml: true });
}
function loadListItems(listTitle){
return $.ajax({
url: _spPageContextInfo.webAbsoluteUrl + "/_api/Web/Lists/GetByTitle('" + listTitle + "')/items?$select=Title,Manager/Title&$expand=Manager",
type: "GET",
headers: {
"accept": "application/json;odata=verbose",
}
});
}
Key points
In my example the list has the following schema:
Field Name Type
Title Text
Manager Lookup
Description Note
List view page
Resulting page

Chart.js with JSON empty

I'm having problems using readings from my json file to fill in the chart. I found a function from here that allows me to pass the api url and returns the JSON data and that works, I then decided to loop through the JSON array adding each reading in an array and then passing that array into the chart function but when I load the page the chart is empty, here is the code `
<!DOCTYPE html>
<html lang="en">
<head>
<script src="Chart.js"></script>
</head>
<body>
<canvas id="myChart" width="400" height="400"></canvas>
<div id="result"></div>
<script>
var getJSON = function(url) {
return new Promise(function(resolve, reject) {
var xhr = new XMLHttpRequest();
xhr.open('get', url, true);
xhr.responseType = 'json';
xhr.onload = function() {
var status = xhr.status;
if (status == 200) {
resolve(xhr.response);
} else {
reject(status);
}
};
xhr.send();
});
};
var json = getJSON('http://ec2-54-152-138-146.compute-1.amazonaws.com:9000/system/listSystems').then(function(data) {
alert(data.data[0].waterLevel);
var chartData =[];
for (var i = 0; i < data.length; i++){
chartData.push(data.data[i].waterLevel);
}
alert(chartData);
var barData = {
labels: ['Italy', 'UK', 'USA', 'Germany', 'France', 'Japan'],
datasets: [
{
label: '2010 customers #',
fillColor: '#382765',
data: chartData
},
{
label: '2014 customers #',
fillColor: '#7BC225',
data: chartData
}
]
};
var context = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(context).Bar(barData)
result.innerText = data.data; //display the result in an HTML element
},
function(status) { //error detection....
alert('Something went wrong.');
});</script>
</body>
</html>
Your loop is incorrect, look at the stop condition in the for cycle.
You have to use data.data.length instead of data.length:
For reference:
for (var i = 0; i < data.data.length; i++)
Change
for (var i = 0; i < data.length; i++)
to
for (var i = 0; i < data.data.length; i++)

Categories