google visualization datatable not going to csv - javascript

Been messing around with this on google playground, and it appears to work without any errors. However when I go to do the export options it doesn't give me anything. Any idea?
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<title>
Google Visualization API Sample
</title>
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load('visualization', '1', {packages: ['table']});
</script>
<script type="text/javascript">
function drawVisualization() {
// Create and populate the data table.
var data = google.visualization.arrayToDataTable([
['Name', 'Height', 'Smokes'],
['Tong Ning mu', 174, true],
['Huang Ang fa', 523, false],
['Teng nu', 86, true]
]);
var options = { 'showRowNumber': true };
options['page'] = 'enable';
options['pageSize'] = 3;
options['pagingSymbols'] = { prev: 'prev', next: 'next' };
options['pagingButtonsConfiguration'] = 'auto';
var components = [
{ type: 'html', datasource: data },
{ type: 'csv', datasource: data }
];
var container = document.getElementById('toolbar_div');
google.visualization.drawToolbar(container, components);
// Create and draw the visualization.
visualization = new google.visualization.Table(document.getElementById('table'));
visualization.draw(data, options);
}
google.setOnLoadCallback(drawVisualization);
</script>
</head>
<body style="font-family: Arial;border: 0 none;">
<div id="table"></div>
<dov id="toolbar_div"></div>
</body>
</html>
​

According to the documentation you have to pass the data through a URL and not any hand-populated data objects. See:
https://developers.google.com/chart/interactive/docs/gallery/toolbar
Usage
To use a toolbar, your visualization must get its data from a URL; you cannot pass in hand-populated DataTable or DataView objects. You will pass the URL of the data used to populate your visualization into the drawToolbar() method.

Code:
$('#Export').click(function () {
var csvFormattedDataTable = google.visualization.dataTableToCsv(data);
var encodedUri = 'data:application/csv;charset=utf-8,' + encodeURIComponent(csvFormattedDataTable);
this.href = encodedUri;
this.download = 'table-data.csv';
this.target = '_blank';
});
Explanation:
Check my answer posted here for an explanation of the code. Export is the Id of the anchor element on the page with the download option.

Related

Not able to render heatmap using heatmap.js

I want to make a project where I can display the different sensor values from differens sensors in a room on a heatmap. The sensor values are stored in a MySQL database, and I want to use the heatmap.js library for the visualisation of this heatmap.
I used an example project from the library creator himself, but I am not able to render it and I just see my header and footer. What am I doing wrong?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="main.css">
</head>
<body>
<?php
include_once ('header.php');
?>
<main>
<script src="heatmap.js"></script>
<div class="heatmap"></div>
<script>
// minimal heatmap instance configuration
var heatmapInstance = h337.create({
// only container is required, the rest will be defaults
container: document.querySelector('.heatmap')
});
// now generate some random data
var points = [];
var max = 0;
var width = 840;
var height = 400;
var len = 200;
while (len--) {
var val = Math.floor(Math.random()*100);
max = Math.max(max, val);
var point = {
x: Math.floor(Math.random()*width),
y: Math.floor(Math.random()*height),
value: val
};
points.push(point);
}
// heatmap data format
var data = {
max: max,
data: points
};
// if you have a set of datapoints always use setData instead of addData
// for data initialization
heatmapInstance.setData(data);
</script>
</main>
<?php
include_once ('footer.php');
?>
</body>

Run a script only after another one completes

I have multiple scripts in my HTML header. the two of concern are as follows:
1) JS script ('Infected Data') produces an object with data. The data is retrieved and computed from a google scripts file, so naturally it takes a bit.
2) A script which generates a map. The map is color coded depending on the values of the Infected Object Data.
The problem is the map loads before i can get the object, so it is not colored.
Map should look like this:
Map looks like this:
HTML Header:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>JQVMap - World Map</title>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type">
<link href="../dist/jqvmap.css" media="screen" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<script type="text/javascript" src="../dist/jquery.vmap.js"></script>
<script type="text/javascript" src="../dist/maps/jquery.vmap.world.js" charset="utf-8"></script>
<script type="text/javascript" src="js/jquery.vmap.sampledata.deaths.js"></script>
<script type="text/javascript" src="js/jquery.vmap.sampledata.infected.js"></script>
<script>
jQuery(document).ready(function () {
jQuery('#vmap').vectorMap({
map: 'world_en',
backgroundColor: '#333333',
color: '#ffffff',
hoverOpacity: 0.8,
selectedColor: '#3498DB',
enableZoom: true,
showTooltip: true,
scaleColors: ['#F3A291', '#FF4F3B'],
values: infected_data,
normalizeFunction: 'polynomial',
onLabelShow: function(event, label, code)
{
// Remove for Russian Joke
/*if (code == 'ru')
{
// Plain TEXT labels
label.text('Bears, vodka, balalaika');
}
else*/
label.html('<div class="map-tooltip"><h1 class="header">'+label.html()+'</h1><p class="description">Infected: '+infected_data[code]+'</p><p class="description">Deaths: '+death_data[code]+'</p></div>');
/*else if (code == 'us')
{
label.html(label.html()+' (GDP - '+sample_data[code]+')');
}*/
},
/*onRegionOver: function(event, code)
{
if (code == 'ca')
{
event.preventDefault();
}
}, */
});
});
</script>
</head>
Infected Data JS FIle:
var infected_dataINT = {};
var infected_data = {};
const url = "https://script.google.com/macros/s/AKfycbzsyQNJwDvQc5SvNGEDZZOoNI3XxNar9PA9sRucZx7mgzfWpFQ/exec";
// Declare an async function
const getData = async () => {
// Use the await keyword to let JS know this variable has some latency so it should wait for it to be filled
// When the variable is fetched, use the .then() callback to carry on
const DataJSON = await fetch(url).then(response =>
response.json()
)
return await DataJSON
};
console.log(getData());
getData().then(result => {
console.log(result);
infected_dataINT = result;
console.log(infected_dataINT);
function toString(o) {
Object.keys(o).forEach(k => {
if (typeof o[k] === 'object') {
return toString(o[k]);
}
o[k] = '' + o[k];
});
return o;
}
console.log(toString(infected_dataINT));
infected_data = toString(infected_dataINT);
})
How can i slow down the jQuery(document).ready(function () {.... to run only after <script type="text/javascript" src="js/jquery.vmap.sampledata.infected.js"></script> has ran
You can dynamically append the script element to the document after the response has been recieved from the server like this:
let script = document.createElement('script');
script.src = 'myJqueryFile.js';
document.head.appendChild(script);
You just have to put those jquery codes inside a .js file.
Sounds like an asynch problem...
Where do you close the header?
</head>
And where is your onload event to synchrinise things?
<body onload="Function_That_KickStarts_Everything();">
Please use the correct document structure and ensure everything begins with the ONLOAD event so that 3rd party libraries may all load and synchronize... follow this please:
<html>
<head>
<style type="text/css">
</style>
</head>
<body onload="Function_That_KickStarts_Everything();">
<script src="Third_Party_Library_1.js"></script>
<script src="Third_Party_Library_2.js"></script>
<script type="text/javascript">
</script>
</body>
</html>

canvasjs live updating data from database

I am new to web based visualization tool I used chartjs before but I did not find any solution for chartjs so, I transferred to canvasjs.Now I'm done creating the chart and it is successfully shown, thus I want to make it moving without refreshing because the data from the database is constantly moving. Here is my code:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title></title>
<script type="text/javascript" src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>
<script type="text/javascript" src="https://canvasjs.com/assets/script/jquery-1.11.1.min.js"></script>
<script type="text/javascript">
window.onload = function () {
$.getJSON("json.php", function(result){
var dps= [];
//Insert Array Assignment function here
for(var i=0; i<result.length;i++) {
dps.push({"label":result[i].ts, "y":result[i].ph});
}
//Insert Chart-making function here
var chart = new CanvasJS.Chart("chartContainer", {
zoomEnabled:true,
panEnabled:true,
animationEnabled:true,
title:{
text: "myChart from mySQL database"
},
axisX:{
title: "TimeStamp"
},
axisY:{
title: "myDataPoints",
minimum: 0
},
data: [{
type: "spline",
dataPoints:
dps
}]
});
chart.render();
});
}
</script>
</head>
<body>
<div id="chartContainer" style="width: 800px; height: 380px;"></div>
</body>
</html>
now, I would like to ask for help out there What do I need to keep this chart moving...??
If you want the lines to move, you need to remove dataPoints from the beginning of the array. You can do so using shift function in JS.
for(var i=0; i<result.length;i++) {
dps.push({"label":result[i].ts, "y":result[i].ph});
dps.shift();
}
This would do the trick for you.

Displaying specific data from a CSV/JSON file

I want to display specific fields from an external CSV file on a web site with using JavaScript.
I tried to parse that file with using "Papa parse" like this:
<!DOCTYPE html>
<html >
<head>
<meta charset="UTF-8">
<title>Parse remote CSV to HTML Page</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<script src='http://d3js.org/d3.v3.min.js'></script>
<script src='https://code.jquery.com/jquery-2.1.4.min.js'></script>
<script src='https://cdnjs.cloudflare.com/ajax/libs/PapaParse/4.1.2/papaparse.min.js'></script>
<script src='https://cdnjs.cloudflare.com/ajax/libs/mustache.js/2.2.0/mustache.min.js'></script>
<script>
Papa.parse("https://dl.dropboxusercontent.com/s/....../data.csv?dl=0", {
download: true,
header: true,
complete: function(results) {
console.log(results);
}
});
</script>
</body>
</html>
And this give me the result in console:
console.log
My question is;
How can I display a specific data from this data set in a web site like:
Battery Level: 0.62
Altimeter Pressure: 99.44185
Horizontal Accuracy: 65
etc. etc.
Taking Battery Level as an example (the other fields are similar and you should be able to figure it out youself):
var data = results.data
var arrayLength = data.length;
for (var i = 0; i < arrayLength; i++) {
var newdiv = document.createElement('div');
newdiv.setAttribute('id', 'your_div_id_'+i.toString());
newdiv.innerHTML = 'Battery Level: '+data[i].batteryLevel.toString();
}

Can't get rid of XML in "variables"

This is involving Intuit's Quickbase. I am trying to use Highcharts.JS and have the data loaded via XML into the graph. The problem I am currently having is that in the variables I have two variables that do not need to be on the graph that relate to something else entirely.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>CoT</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript" src="https://code.highcharts.com/highcharts.js"></script>
<!-- JavaScript to initialize the chart on document ready -->
<script type="text/javascript">
$(document).ready(function() {
var options = {
chart: {
renderTo: 'container',
type: 'column'
},
title: {
text: 'Components Over Time'
},
xAxis: {
categories: []
},
yAxis: {
title: {
text: 'Units'
}
},
series: []
};
// Load the data from the XML file
$.get('https://dbname.quickbase.com/db/?apptoken=&act=API_DoQuery&query=%7B14.EX.%27_FID_9%7D&clist=7.24.25.26.27.28.29.30.31.32.33.34.35.36.37', function(xml) {
// Split the lines
var $xml = $(xml);
// push categories
$xml.find('variables').each(function(i, variables) {
options.xAxis.categories.push($(variables).text());
});
// push series
$xml.find('record').each(function(i, record) {
var seriesOptions = {
name: $(record).find('methane').text(),
data: [],
};
// push data points
$(record).find('methane').each(function(i, point) {
seriesOptions.data.push(
parseInt($(point).text())
);
});
// add it to the options
options.series.push(seriesOptions);
});
var chart = new Highcharts.Chart(options);
});
});
</script>
</head>
<body>
<!-- 3. Add the container -->
<div id="container" style="width: 800px; height: 400px; margin: 0 auto"></div>
</body>
</html>
The following has also been tried in the push categories to no success
$xml.find('variables:not(iol):not(__iol)').each(function(i, variables) {
options.xAxis.categories.push($(variables).text());
});
Both cause the graph to come back looking like ( http://i.imgur.com/fb8A2uO.jpg )
Edit: This is the XML output
<?xml version="1.0" ?>
<qdbapi>
<action>API_DoQuery</action>
<errcode>0</errcode>
<errtext>No error</errtext>
<dbinfo>
<name>RESULT</name>
<desc></desc>
</dbinfo>
<variables>
<__iol>&rand='+new Date().getTime())};"></__iol>
<iol><img qbu='module' src='/i/clear2x2.gif' onload="javascript:if(typeof QBU=='undefined'){QBU={};$.getScript(gReqAppDBID+'?a=dbpage&pagename=</iol>
</variables>
<chdbids>
</chdbids>
<record>
<sample_date>1386892800000</sample_date>
<hydrogen>0.002</hydrogen>
<helium>0.114</helium>
<oxygen/>
<hydrogen_sulfide/>
<nitrogen>1.926</nitrogen>
<co2>0.454</co2>
<methane>82.163</methane>
<ethane>6.353</ethane>
<propane>4.760</propane>
<iso_butane>0.618</iso_butane>
<n_butane>1.819</n_butane>
<iso_pentane>0.491</iso_pentane>
<n_pentane>0.544</n_pentane>
<hexanes_>0.756</hexanes_>
<update_id>1408654196361</update_id>
</record>
<record>
<sample_date>1383782400000</sample_date>
<hydrogen>0.006</hydrogen>
<helium>0.038</helium>
<oxygen/>
<hydrogen_sulfide/>
<nitrogen>0.512</nitrogen>
<co2>0.844</co2>
<methane>83.178</methane>
<ethane>8.678</ethane>
<propane>3.631</propane>
<iso_butane>0.493</iso_butane>
<n_butane>1.097</n_butane>
<iso_pentane>0.342</iso_pentane>
<n_pentane>0.371</n_pentane>
<hexanes_>0.810</hexanes_>
<update_id>1408981434690</update_id>
</record>
<record>
<sample_date>1369699200000</sample_date>
<hydrogen>0.004</hydrogen>
<helium>0.060</helium>
<oxygen/>
<hydrogen_sulfide/>
<nitrogen>1.684</nitrogen>
<co2>0.443</co2>
<methane>77.742</methane>
<ethane>10.430</ethane>
<propane>6.842</propane>
<iso_butane>0.587</iso_butane>
<n_butane>1.482</n_butane>
<iso_pentane>0.232</iso_pentane>
<n_pentane>0.249</n_pentane>
<hexanes_>0.245</hexanes_>
<update_id>1408981112624</update_id>
</record>
</qdbapi>
Try
// note the space character between tags ,
// to prevent rendering `<variables />` within xml
$xml.find("variables").replaceWith("<variables> </variables>");
http://jsfiddle.net/xwzox6rg/

Categories

Resources