How to draw google barchart using dynamic data from Json - javascript

I am trying to get Json data using the $.getJSON() method.
And this is the result:
Hcount:29Acount:0Pcount:12Ccount:0
I wanted to draw a bar chart using the result count with the help of the google chart API so I used the getbar() method. But nothing happenes after passing the getbar() method.
Here is the Javascript and HTML code:
function getStats() {
var obj1="";
$.getJSON('getbusinessstats', function(response) {
var txnSource = "";
$.each(response.tanSource, function(key, value) {
tanSource += key+":"+value
});
obj1={ "Array1": [tanSource] };
alert(obj1.Array1)
getbar(obj1);
//$('#vis_div tbody').html(tanSource);
});
}
function getbar(obj2)
{
google.load('visualization', '1');
google.setOnLoadCallback(drawVisualization);
function drawVisualization() {
var wrapper = new google.visualization.ChartWrapper({
chartType: 'ColumnChart',
dataTable: [obj2],
options: {'title': 'INPUT'},
containerId: 'vis_div'
});
wrapper.draw();
}
}
$(document).ready(function() {
getStats();
setInterval(function() {
getStats();
}, 5000);
});
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
<script src="lib/jquery-1.11.1.js"></script>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
</head>
<body>
<div >
<span class="label label-info">INPUT </span>
<table id="vis_div">
<tbody>
</tbody>
</table>
</div>
</body>
</html>

Related

Google Visualization API load 2 scripts on the same HTML

Hello Im trying to load 2 scripts at the same page but they seem to be overlapping eachother.In the first script im getting a table with a few columns and cells. In the 2nd one im getting just a single cell from the second sheet tab but as i said they overlap eachother and i can see only one at a time. This is my first time using google visualizations and i tried to rename the variables and names but i get the same thing.Is there a way to merge both scripts in one and have the html page load both of them without overlapping. Thank you.
<!DOCTYPE html>
<html class="no-js" lang="en">
<head>
<meta charset="utf-8">
<link href="https://fonts.googleapis.com/css?family=Open+Sans:300,400,700" rel="stylesheet">
<link href="css/normalize.css" rel="stylesheet">
<link href="css/main.css" rel="stylesheet">
<script src="https://www.gstatic.com/charts/loader.js" type="text/javascript"></script>
</head>
<body >
<div id="box">
<script src="js/google-sheets-html.js" type="text/javascript"></script>
<div id="table">
</div>
</div>
<div id="box2">
<script src="js/google-sheets-html2.js" type="text/javascript"></script>
<div id="table2">
</div>
</div>
</body>
</html>
First Script
google.load('visualization', '1', {
packages: ['table']
});
var visualization;
function drawVisualization() {
var query = new google.visualization.Query('https://spreadsheets.google.com/tq?key=xxx&output=html&usp=sharing');
query.setQuery('SELECT A, B, C, D, E, F, G ,H ,I ORDER BY A DESC Limit 10 label A "Date", B "Agent", C "Client", D "Country", E "Desk", F "Department", G "Method", H "Amount", I "Currency"');
query.send(handleQueryResponse);
}
function handleQueryResponse(response) {
if (response.isError()) {
alert('There was a problem with your query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
return;
}
var data = response.getDataTable();
visualization = new google.visualization.Table(document.getElementById('table'));
visualization.draw(data, {
allowHtml: true,
legend: 'bottom'
});
}
google.setOnLoadCallback(drawVisualization);
Second Script
google.load('visualization', '1', {
packages: ['table']
});
var visualization;
function drawVisualization() {
var query = new google.visualization.Query('https://docs.google.com/spreadsheets/d/xxx/gviz/tq?gid=xxx');
query.setQuery('SELECT A');
query.send(handleQueryResponse);
}
function handleQueryResponse(response) {
if (response.isError()) {
alert('There was a problem with your query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
return;
}
var data = response.getDataTable();
visualization = new google.visualization.Table(document.getElementById('table2'));
visualization.draw(data, {
allowHtml: true,
legend: 'bottom'
});
}
google.setOnLoadCallback(drawVisualization);
combine them into one script.
you only need to load google charts once,
regardless the number of tables / charts being drawn.
see following snippets...
HTML
<html class="no-js" lang="en">
<head>
<meta charset="utf-8">
<link href="https://fonts.googleapis.com/css?family=Open+Sans:300,400,700" rel="stylesheet">
<link href="css/normalize.css" rel="stylesheet">
<link href="css/main.css" rel="stylesheet">
<script src="https://www.gstatic.com/charts/loader.js" type="text/javascript"></script>
</head>
<body >
<div id="box">
<div id="table">
</div>
</div>
<div id="box2">
<div id="table2">
</div>
</div>
<script src="js/google-sheets-html.js"></script>
</body>
</html>
JS
google.charts.load('current', {
packages: ['table']
}).then(function () {
var query = new google.visualization.Query('https://spreadsheets.google.com/tq?key=xxx&output=html&usp=sharing');
query.setQuery('SELECT A, B, C, D, E, F, G ,H ,I ORDER BY A DESC Limit 10 label A "Date", B "Agent", C "Client", D "Country", E "Desk", F "Department", G "Method", H "Amount", I "Currency"');
query.send(function (response) {
handleQueryResponse(response, 'table');
});
var query = new google.visualization.Query('https://docs.google.com/spreadsheets/d/xxx/gviz/tq?gid=xxx');
query.setQuery('SELECT A');
query.send(function (response) {
handleQueryResponse(response, 'table2');
});
function handleQueryResponse(response, id) {
if (response.isError()) {
alert('There was a problem with your query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
return;
}
var data = response.getDataTable();
visualization = new google.visualization.Table(document.getElementById(id));
visualization.draw(data, {
allowHtml: true,
legend: 'bottom'
});
}
});

How to read particular column range row count in AngularJS

I am working in excel import functionality in AngularJS. Now it's working fine by reading excel values. But I need read a particular column range row count
here I attached my tried code and expected output. Here I get row count as 7 but I need name and subject column row count only expected row count as 4 help how to solve this problem.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Angular Js XLS</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.9.13/xlsx.full.min.js"></script>
<script type="text/javascript" src="https://unpkg.com/angular-js-xlsx#0.0.3/angular-js-xlsx.js"></script>
</head>
<body ng-app="MyApp">
<div ng-controller="myController">
<js-xls onread="read" onerror="error"></js-xls>
<!-- <input type="file" ng-change="read" onerror="error"> -->
</div>
</body>
<script type="text/javascript">
angular.module('MyApp', ['angular-js-xlsx'])
.controller('myController', function($scope) {
$scope.read = function (workbook) {
debugger;
var headerNames = XLSX.utils.sheet_to_json( workbook.Sheets[workbook.SheetNames[0]], { header: 1 })[0];
var data = XLSX.utils.sheet_to_json( workbook.Sheets[workbook.SheetNames[0]]);
console.log(headerNames);
console.log(data);
for (var row in data)
{
Object.keys(data[row]).forEach(function(key) {
console.log("Key = >" + key);
console.log("Value => " + data[row][key]);
console.log("===========================");
});
}
}
$scope.error = function (e) {
console.log(e);
}
});
</script>
</html>
Data

Dojo - hello world - using CDN module - get it work

When reading the introduction of Dojo, I followed (as newbie) the hello world tutorial.
How can I get this local demo working (via the CDN approach)? Afer a POC I will put it on a webserver, etc.
Step 1: I copied the module into the demo folder:
define([
'dojo/dom'
], function(dom){
var oldText = {};
return {
setText: function (id, text) {
var node = dom.byId(id);
oldText[id] = node.innerHTML;
node.innerHTML = text;
},
restoreText: function (id) {
var node = dom.byId(id);
node.innerHTML = oldText[id];
delete oldText[id];
}
};
});
Then in the current folder I put the Html file:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Tutorial: Hello Dojo!</title>
</head>
<body>
<h1 id="greeting">Hello</h1>
<script>
var dojoConfig = {
async: true,
packages: [{
name: "demo",
location: location.pathname.replace(/\/[^/]*$/, '') + '/demo'
}]
};
</script>
<script src="//ajax.googleapis.com/ajax/libs/dojo/1.10.4/dojo/dojo.js"></script>
<script>
require([
'demo/myModule'
], function (myModule) {
myModule.setText('greeting', 'Hello Dojo!');
setTimeout(function () {
myModule.restoreText('greeting');
}, 3000);
});
</script>
</body>
</html>
When double clicking the browser on the Html file, no traffic is seen, no demo text is changed and re-changed.
It was not simple as a newbie to get the Dojo "hello world" running.
The changes are marked with ** ... **
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Tutorial: Hello Dojo!</title>
</head>
<body>
<h1 id="greeting">Hello</h1>
<script>
var dojoConfig = {
async: true,
packages: [{
name: "demo",
**location: 'K:/k_schijf/dojo/demo'**
}]
};
</script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/dojo/1.10.4/dojo/dojo.js"></script>
<script type="text/javascript">
require(
**[ "demo/myDojoModule.js" ],**
function (myDojoModule) {
myDojoModule.setText('greeting', 'Hello Dojo!');
setTimeout(function () {
myDojoModule.restoreText('greeting');
}, 3000);
});
</script>
</body>
</html>
Working "Hello World" example using CDN from Google.
var dojoConfig = {
async: true
};
require(["dijit/form/Button", "dojo/dom", "dojo/domReady!"], function(Button, dom){
// Create a button programmatically:
var myButton = new Button({
label: "Click me!",
onClick: function(){
// Do something:
dom.byId("result1").innerHTML += "Thank you! ";
}
}, "progButtonNode").startup();
});
<link href="https://ajax.googleapis.com/ajax/libs/dojo/1.10.0/dijit/themes/claro/claro.css" rel="stylesheet"/>
<script src="http://ajax.googleapis.com/ajax/libs/dojo/1.10.4/dojo/dojo.js"></script>
<button id="progButtonNode" type="button"></button>
<div id="result1"></div>

Displaying data points from server side txt file on google graph

I would like to display my retrieved data points from my server side text file
on a google graph. During research i can now retrieve the data from my temps.txt
file using $.get().
I just started learning javascript , so this may be something obvious that i missed.
I can also display a sample google graph with some example datapoints.
How can i put the two together? , below i have both source files
from my attempts so far.
Getting the Datapoints:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>load demo</title>
<style>
body {
font-size: 16px;
font-family: Arial;
}
</style>
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<script>
var times = [];
$.get('temps.txt', function(data) {
times = data.split("\n");
var html = [];
for (var i in times) {
html.push(times[i] + '<br/>');
}
html.push( times[0] * 3 );
$('body').append(html.join(''));
});
</script>
</html>
Showing the GRAPH:
<html>
<head>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Hours', 'Temperature'],
['18:00', 20.7],
['19:00', 21],
['20:00', 22.3],
['20:30', 22.5],
['21:00', 22.0],
['22:00', 21.6]
]);
var options = {
title: 'Temperatuur Grafiek',
legend: { position: 'bottom' }
};
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
</head>
<body>
<div id="chart_div" style="width: 700px; height: 400px;"></div>
</body>
</html>
Temps.txt file is a simple text file with one measured value every hour
the first line is 00:00 hrs the 2nd line 01:00 hrs and so on see below:
15.3
16.4
16.7
18.8
... etc
Well, would be something like this:
function drawChart() {
$.get('temps.txt', function(txt) {
vals = txt.split("\n");
var hour= 0;
var dataArr=[['Hours', 'Temperature']]
for(var i = 0; i < vals.length;i++){ // build data array
//add the hour in 'hh:00' format and the temperature value
dataArr.push([('0'+hour).substring(-2)+':00', parseFloat(vals[i])]);
hour+=1;
}
var data = google.visualization.arrayToDataTable(dataArr)
var options = {
title: 'Temperatuur Grafiek',
legend: { position: 'bottom' }
};
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
});
}

HighCharts reading from CSV basic example

Am new to highcharts and JS and am trying to plot data from a csv file (data3.csv).
Here is the code at the moment:
<!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>Highcharts Example</title>
<!-- 1. Add these JavaScript inclusions in the head of your page -->
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript" src="highcharts.js"></script>
<!--[if IE]>
<script type="text/javascript" src="../js/excanvas.compiled.js"></script>
<![endif]-->
<!-- 2. Add the JavaScript to initialize the chart on document ready -->
<script type="text/javascript">
$(document).ready(function() {
var options = {
chart: {
renderTo: 'container',
defaultSeriesType: 'line'
},
title: {
text: 'Stock Chart'
},
xAxis: {
categories: []
},
yAxis: {
title: {
text: 'Price'
}
},
series: []
};
$.get('data3.csv', function(data) {
$.each(lines, function(lineNo, line) {
var items = line.split(',');
var series = {
data: []
};
$.each(items, function(itemNo, item) {
if (itemNo == 0) {
series.name = item;
} else {
series.data.push(parseFloat(item));
}
});
options.series.push(series);
});
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>
And the contents of the csv file are:
Date Open
29/01/2010 538.49
28/01/2010 544.49
27/01/2010 541.27
26/01/2010 537.97
25/01/2010 546.59
However, this is not giving a chart (just gives the title).
Could anyone suggest where I am going wrong?
Thanks
In line
var items = line.split(',');
You should spline csv by commas, but you have space. So you can replace this line with:
var items = line.split(' ');
or generate csv which items will separated by comma.
As a result your parser should looks like:
$.get('data.csv', function(data) {
// Split the lines
var lines = data.split('\n');
// Iterate over the lines and add categories or series
$.each(lines, function(lineNo, line) {
var items = line.split(',');
if(lineNo>0)
{
options.xAxis.categories.push(items[0]); //set first column from CSV as categorie
options.series[0].data.push(parseFloat(items[1])); //set second column from CSV as point value
}
});
// Create the chart
var chart = new Highcharts.Chart(options);
});

Categories

Resources