I have created a web server on ESP8266 that uses Google gauge to display current temperature data and line graph to display previous data. The gauge and line graph will update as new data come in. Everything works well and when I call the IP the line graph will display and start to populate. The problem is that every IP call the line graph starts with no data and populates all over again because when dataTable is initialized it is returning a new empty data table. Can anyone make a suggestion on creating a line graph from the existing data array in the datatable when make IP call? Thanks.
Code to update line graph:
<!DOCTYPE html>
<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','gauge']});
google.charts.setOnLoadCallback(drawChart);
function drawChart(){
//Create opening gauges
var gaugeData = google.visualization.arrayToDataTable([
['Label', 'Value'],
['Room 1', 0],
['Room 2', 0]
]);
var gaugeOptions = {
width: 800, height: 240,
redFrom: 90, redTo: 100,
yellowFrom:75, yellowTo: 90,
minorTicks: 5
};
var chart = new google.visualization.Gauge(document.getElementById('chart_div'));
chart.draw(gaugeData, gaugeOptions);
//Obtain new temperature data and update gauge and line graph
setInterval(updateValues, 3000);
function updateValues() {
//Obtain Room 1 temperature and update Google Gauge
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState === 4 && this.status === 200) {
Room1temp = parseFloat(this.responseText);
gaugeData.setValue(0, 1, Room1temp);
chart.draw(gaugeData, gaugeOptions);
}
};
xhttp.open("GET", "/Room1temp", true);
xhttp.send();
//Obtain Room 2 temperature and update Google Gauge
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState === 4 && this.status === 200) {
Room2temp = parseFloat(this.responseText);
gaugeData.setValue(1, 1, Room2temp);
chart.draw(gaugeData, gaugeOptions);
}
};
xhttp.open("GET", "/Room2temp", true);
xhttp.send();
};
//Update Google line chart with timestamp and Room 1 & 2 temperatures
var data = new google.visualization.DataTable();
data.addColumn('datetime', 'Time');
data.addColumn('number', 'Room 1');
data.addColumn('number', 'Room 2');
setInterval(updateGraph, 3000);
function updateGraph() {
//create timestamp
let date = new Date();
var Year = date.getFullYear();
var Month = date.getMonth();
var Day = date.getDate();
var Hour = date.getHours();
var Min = date.getMinutes();
var Sec = date.getSeconds();
//Update line graph
if(data.getNumberOfRows()<5){
data.addRows([
[new Date(Year,Month,Day,Hour,Min,Sec), parseFloat(Room1temp), parseFloat(Room2temp)]
]);
} else {
var view = new google.visualization.DataView(data);
data.addRows([
[new Date(Year,Month,Day,Hour,Min,Sec), parseFloat(Room1temp), parseFloat(Room2temp)]
]);
data.removeRow(0);
}
var options = {
title: 'Temperature Data',
pointSize: 8
};
var chart = new google.visualization.LineChart(document.getElementById('curve_chart'));
chart.draw(data, options);
}; //End function updateGraph
} // End function drawChart
</script>
</head>
<body>
<div id="chart_div" style="width:600px;margin-left:auto;margin-right:auto"></div>
<div id="curve_chart" style="width:1400px;margin-left:auto;margin-right:auto"></div>
</body>
</html>
try making the IP calls in succession, waiting for each to complete,
before continuing to the next and updating the charts.
see following snippet...
google.charts.load('current', {
packages: ['corechart', 'gauge']
}).then(function () {
//Create opening gauges
var gaugeData = google.visualization.arrayToDataTable([
['Label', 'Value'],
['Room 1', 0],
['Room 2', 0]
]);
var gaugeOptions = {
width: 800, height: 240,
redFrom: 90, redTo: 100,
yellowFrom:75, yellowTo: 90,
minorTicks: 5
};
var gaugeChart = new google.visualization.Gauge(document.getElementById('chart_div'));
gaugeChart.draw(gaugeData, gaugeOptions);
// line chart
var data = new google.visualization.DataTable();
data.addColumn('datetime', 'Time');
data.addColumn('number', 'Room 1');
data.addColumn('number', 'Room 2');
var chart = new google.visualization.LineChart(document.getElementById('curve_chart'));
var options = {
title: 'Temperature Data',
pointSize: 8
};
//Obtain new temperature data and update gauge and line graph
setInterval(updateValues, 3000);
function updateValues() {
//Obtain Room 1 temperature and update Google Gauge
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState === 4 && this.status === 200) {
var Room1temp = parseFloat(this.responseText);
gaugeData.setValue(0, 1, Room1temp);
gaugeChart.draw(gaugeData, gaugeOptions);
//Obtain Room 2 temperature and update Google Gauge
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState === 4 && this.status === 200) {
var Room2temp = parseFloat(this.responseText);
gaugeData.setValue(1, 1, Room2temp);
gaugeChart.draw(gaugeData, gaugeOptions);
//Update line graph
if(data.getNumberOfRows()<5){
data.addRows([
[new Date(), parseFloat(Room1temp), parseFloat(Room2temp)]
]);
} else {
data.addRows([
[new Date(), parseFloat(Room1temp), parseFloat(Room2temp)]
]);
data.removeRow(0);
}
chart.draw(data, options);
}
};
xhttp.open("GET", "/Room2temp", true);
xhttp.send();
}
};
xhttp.open("GET", "/Room1temp", true);
xhttp.send();
};
});
Related
I am trying to making dynamic Google Line chart. I am fetching my datatable from Google Sheet.
I added eventlistener in html to update the data row. So that, existing data row gets updated.
My aim is to delete existing data rows from the chart and new data rows.
Code.gs:
function getTableDataTV(){
//Chart load with this datatable
const ws = SpreadsheetApp.openById("").getSheetByName("Sheet 1"); //2nd worksheet ID
const data = ws.getRange (2,1,ws.getLastRow() -1, 9).getDisplayValues();
return data
}
function getvoddata() {
//new data table for eventlistener
const ss = SpreadsheetApp.openById("");//2nd worksheet ID
const sw = ss.getSheetByName("Sheet 2");
var finaldata = sw.getRange (2,1,sw.getLastRow() -1, 9).getDisplayValues();
return finaldata
}
HTML:
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.load('current', {'packages':['line']});
google.charts.setOnLoadCallback(getData);
var chart;
var options;
function getData(){
google.script.run.withSuccessHandler(drawChart).getTableDataTV();
}
function drawChart(dataReturned) {
data = new google.visualization.DataTable();
data.addColumn('date', 'Days');
data.addColumn('number', 'A');
data.addColumn('number', 'B');
data.addColumn('number', 'C');
data.addColumn('number', 'D');
var newData = dataReturned.map(r => [new Date(r[0].slice(6,10),r[0].slice(0,2),r[0].slice(3,5)), parseInt(r[1]),parseInt(r[2]),parseInt(r[3]),parseInt(r[4])]);
data.addRows(newData);
options = {
title: 'Total Views',
subtitle: 'ABP News Vs Competitor Channels'
};
chart = new google.charts.Line(document.getElementById('chart'));
chart.draw(data, google.charts.Line.convertOptions(options));
}
//Update Data Row
document.getElementById("pd1").addEventListener("click",newchart);
function newchart(){
google.script.run.withSuccessHandler(updateChart).getvoddata();
}
function updateChart(newdataReturned) {
data = new google.visualization.DataTable();
data.addColumn('date', 'Days');
data.addColumn('number', 'A');
data.addColumn('number', 'B');
data.addColumn('number', 'C');
data.addColumn('number', 'D');
var newData = newdataReturned.map(r => [new Date(r[0].slice(6,10),r[0].slice(0,2),r[0].slice(3,5)), parseInt(r[1]),parseInt(r[2]),parseInt(r[3]),parseInt(r[4])]);
data.addRows(newData);
// redraw the chart.
chart.draw(data, options);
}
</script>
.....
<body>...
<a id="pd1">VOD</a>
<div id="chart" style="width: 1000px; height: 400px"></div>
</body>
I am also getting error on console when add below line:
document.getElementById("pd1").addEventListener("click",newchart);
Error:
Uncaught TypeError: document.getElementById(...) is null
I got this updatefunction from this website and it is working on jsfiddle.
Please check, what I am doing wrong here.
Thank You
In your situation, how about the following modification?
Modified script:
In this modification, your HTML and Javascript are modified. I thought that when I saw your HTML and Javascript, the button is not shown in your HTML, and also, the container for inserting the chart is not shown. And, when I modified your HTML and Javascript by these situations and your sample script shown in your jsfiddle.
<div id="chart"></div>
<button id="pd1">update chart</button>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script>
google.load("visualization", "1", { packages: ["corechart"] });
google.setOnLoadCallback(getData);
var chart;
var data;
var options;
document.getElementById("pd1").addEventListener("click", newchart);
function getData() {
google.script.run.withSuccessHandler(drawChart).getTableDataTV();
}
function newchart() {
google.script.run.withSuccessHandler(updateChart).getvoddata();
}
function drawChart(dataReturned) {
data = new google.visualization.DataTable();
data.addColumn('date', 'Days');
data.addColumn('number', 'A');
data.addColumn('number', 'B');
data.addColumn('number', 'C');
data.addColumn('number', 'D');
var newData = dataReturned.map(r => [new Date(r[0].slice(6, 10), r[0].slice(0, 2), r[0].slice(3, 5)), parseInt(r[1]), parseInt(r[2]), parseInt(r[3]), parseInt(r[4])]);
data.addRows(newData);
options = { title: 'Total Views', subtitle: 'ABP News Vs Competitor Channels' };
chart = new google.visualization.LineChart(document.getElementById('chart'));
chart.draw(data, options);
}
function updateChart(newdataReturned) {
data = new google.visualization.DataTable();
data.addColumn('date', 'Days');
data.addColumn('number', 'A');
data.addColumn('number', 'B');
data.addColumn('number', 'C');
data.addColumn('number', 'D');
var newData = newdataReturned.map(r => [new Date(r[0].slice(6, 10), r[0].slice(0, 2), r[0].slice(3, 5)), parseInt(r[1]), parseInt(r[2]), parseInt(r[3]), parseInt(r[4])]);
data.addRows(newData);
chart.draw(data, options);
}
</script>
Note:
In this modification, it supposes that your functions getTableDataTV() and getvoddata() at Google Apps Script return the correct values you expect. Please be careful this.
I'm attempting to pull data from Google Sheets and use it as a source for my Gantt chart. I've followed the example in the Google Charts documentation for pulling Sheets data for a columnchart, but not sure if more customization is necessary.
I'm not as familiar with Javascript, so not sure what is triggering the error. Here is the code in JSFiddle.
google.charts.load('current', {'packages':['gantt']});
google.charts.setOnLoadCallback(drawChart);
function daystoMilliseconds(days) {
return days * 24 * 60 * 60 * 1000;
}
function drawGID() {
var queryString = encodeURIComponent('SELECT A, B, C, D, E, F, G, H');
var query = new google.visualization.Query(
'https://docs.google.com/spreadsheets/d/1f0wxDrEfptRKCRY5pQPu6Dc_ue_tIX_ja5pQO3vXjOY/edit#gid=0&headers=1&tq=' + queryString);
query.send(handleSampleDataQueryResponse);
}
function handleSampleDataQueryResponse(response) {
if (response.isError()) {
alert('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
return;
}}
function drawChart() {
var otherData = response.getDataTable();
var options = {
height: 275,
gantt: {
defaultStartDateMillis: new Date(2015, 3, 28)
}
};
var chart = new google.visualization.Gantt(document.getElementById('chart_div'));
chart.draw(otherData, options);
}
first, the callback should be --> drawGID
instead of --> drawChart
next, notice the data format for a Gantt chart
both the 'Start' and 'End' dates are required and cannot be blank,
as in the spreadsheet
see following working snippet...
a new data table is built, using the data from the spreadsheet (otherData),
using the 'Duration' column to fill in the the dates
google.charts.load('current', {
callback: drawGID,
packages: ['gantt']
});
function drawGID() {
var queryString = encodeURIComponent('SELECT A, B, C, D, E, F, G, H');
var query = new google.visualization.Query(
'https://docs.google.com/spreadsheets/d/1f0wxDrEfptRKCRY5pQPu6Dc_ue_tIX_ja5pQO3vXjOY/edit#gid=0&headers=1&tq=' + queryString);
query.send(handleSampleDataQueryResponse);
}
function handleSampleDataQueryResponse(response) {
if (response.isError()) {
alert('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
return;
}
var otherData = response.getDataTable();
var ganttData = new google.visualization.DataTable({cols: [
{type: 'string', label: 'Task Id'},
{type: 'string', label: 'Task Name'},
{type: 'string', label: 'Resource'},
{type: 'date', label: 'Start'},
{type: 'date', label: 'End'},
{type: 'number', label: 'Duration'},
{type: 'number', label: '% Complete'},
{type: 'string', label: 'Dependencies'}
]});
var duration = 0;
var startDate = new Date(2016, 0, 1);
var endDate;
for (var i = 0; i < otherData.getNumberOfRows(); i++) {
startDate = new Date(startDate.getTime() + duration);
duration += otherData.getValue(i, 5);
endDate = new Date(startDate.getTime() + duration);
ganttData.addRow([
otherData.getValue(i, 0),
otherData.getValue(i, 1),
otherData.getValue(i, 2),
startDate,
endDate,
otherData.getValue(i, 5),
parseFloat(otherData.getValue(i, 6)),
otherData.getValue(i, 7)
]);
}
var options = {
height: 275,
gantt: {
defaultStartDateMillis: new Date(2015, 3, 28)
}
};
var chart = new google.visualization.Gantt(document.getElementById('chart_div'));
chart.draw(ganttData, options);
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>
The following Google project allows you to view a Google Spreadsheet as a Gantt Chart:
https://github.com/google/ezgantt
Ive been trying to load data from a SQL table thats generated daily via a SP, Table consists of 4 columns.
My Ajax call gets the data and puts into an array -
Array
Heres my code im using to draw the view and pass the array -
var chartData;
$(document).ready(function () {
$.ajax({
url: "/Reporting/LeaveList",
data: "",
dataType: "json",
type: "POST",
contentType: "application/json; chartset=utf-8",
success: function (data) {
//console.log(data);
console.log(typeof data);
chartData = data;
},
error: function () {
alert("Error loading data! Please try again.");
}
}).done(function () {
google.setOnLoadCallback(createTable);
});
});
function createTable() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Date');
data.addColumn('number', 'AnnualLeave');
data.addColumn('number', 'Sick');
data.addColumn('number', 'Total');
data.addRow(chartData[0])
// Create a dashboard.
var dash_container = document.getElementById('dashboard_div'),
myDashboard = new google.visualization.Dashboard(dash_container);
// Create a date range slider
var myDateSlider = new google.visualization.ControlWrapper({
'controlType': 'ChartRangeFilter',
'containerId': 'control_div',
'options': {
'filterColumnLabel': 'Date'
}
});
// Table visualization
var myTable = new google.visualization.ChartWrapper({
'chartType': 'Table',
'containerId': 'table_div'
});
// Bind myTable to the dashboard, and to the controls
// this will make sure our table is update when our date changes
myDashboard.bind(myDateSlider, myTable);
// Line chart visualization
var myLine = new google.visualization.ChartWrapper({
'chartType': 'LineChart',
'containerId': 'line_div',
});
// Bind myLine to the dashboard, and to the controls
myDashboard.bind(myDateSlider, myLine);
myDashboard.draw(data);
And heres some of the controller -
data = (
from u in db.StaffReportingDay
select new StaffReportingDayVM
{
Date = u.Date.ToString(),
AnnualLeave = u.AnnualLeave,
CompassionateLeave = u.CompassionateLeave,
Sick = u.Sick,
StudyLeave = u.StudyLeave,
Total = u.Total
}).ToList();
}
var ChartOne = new object[data.Count + 1];
ChartOne[0] = new object[]
{
"Date",
"Annual Leave",
"Sick Leave",
"Total on Leave"
};
int j = 0;
foreach(var i in data)
{
j++;
ChartOne[j] = new object[] {i.Date.ToString(), i.AnnualLeave, i.Sick, i.Total };
}
return Json(ChartOne, JsonRequestBehavior.AllowGet);
What i cant get is the array to pull into the view, i just get an error -
Uncaught Error: Type mismatch. Value Annual Leave does not match type number in column index 1
Ive tried many things but would like some pointers and other people to give their insight please.
Solved with
function drawVisualization() {
var data = new google.visualization.DataTable();
data.addColumn('date', 'Date');
data.addColumn('number', 'AnnualLeave');
data.addColumn('number', 'CompassionateLeave');
data.addColumn('number', 'StudyLeave');
data.addColumn('number', 'Sick');
data.addColumn('number', 'Total');
$.each(chartData, function (i, row) {
data.addRow([
(new Date(row.Date)),
parseFloat(row.AnnualLeave),
parseFloat(row.CompassionateLeave),
parseFloat(row.StudyLeave),
parseFloat(row.Sick),
parseFloat(row.Total)
]);
});
I've got a chart that needs to be manipulated with data from the database. Therefore I have converted the data from the database to JSON string. the problem is that I don't know how to integrate the JSON data I received right into the chart.
These are the files needed to make this work:
The php & PDO query:
<?php
/*host = 'localhost' Namecheap default. Could also use 127.0.0.1 */
try {
$connection= new PDO('mysql:host=localhost;dbname=clicrckc_andfit','clicrckc_osherdo','3563077');
$connection->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
$sql="SELECT answer_vegitable,answer_cigarettes,answer_workout FROM answers where user_id=58";
$row=$connection->prepare($sql);
$row->execute();
$result=$row->fetchAll(PDO::FETCH_ASSOC);
$main = array('data'=>$result,'value'=>array("bgcolor"=>"#f1fff1","message"=>"All records displayed"));
echo json_encode($main);
$connection = null;
}
catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
?>
The HTML & JS needed for chart creation and manipluation:
<title>Statistics Chart</title>
<script src="../amcharts_3.13.1.free/amcharts/amcharts.js" type="text/javascript"></script>
<script src="../amcharts_3.13.1.free/amcharts/serial.js" type="text/javascript"></script>
<script type="text/javascript">
AmCharts.loadJSON = function("barClustered.php") {
// create the request
if (window.XMLHttpRequest) { // XMLHttpRequest object is the keystone of AJAX, and it is used to exchange small
//amounts of data with the server.
// IE7+, Firefox, Chrome, Opera, Safari (modern browsers).
var request = new XMLHttpRequest();
} else {
// code for IE6, IE5
var request = new ActiveXObject('Microsoft.XMLHTTP');
}
// load it
// the last "false" parameter ensures that our code will wait before the
// data is loaded
request.open('GET',"barClustered.php", false); //Type of request,The acutal URL, asynchronously or not?
request.send(); // Send request to the server.
// Adding code after the send method in case of synchronous request (like the one above).
// parse and return the output
return eval(request.responseText); // responseText is getting the response data as a string.
};
</script>
<!-- The chart code -->
<script>
var chart;
var chartData = [
{
"questions": "Vegtables Eaten",
"This Week": 30.1,
"Last Week": 23.9,
"2 Weeks Ago": 27.5
},
{
"questions": "Workout (Minutes)",
"This Week": 29.5,
"Last Week": 25.1,
"2 Weeks Ago": 26.4
},
{
"questions": "Cigarettes smoked",
"This Week": 24.6,
"Last Week": 25,
"2 Weeks Ago": 28
}
];
AmCharts.ready(function () {
// SERIAL CHART
chart = new AmCharts.AmSerialChart();
chart.dataProvider = chartData;
chart.categoryField = "questions";
chart.startDuration = 1;
chart.plotAreaBorderColor = "#DADADA";
chart.plotAreaBorderAlpha = 1;
// this single line makes the chart a bar chart
chart.rotate = true;
// AXES
// Category
var categoryAxis = chart.categoryAxis;
categoryAxis.gridPosition = "start";
categoryAxis.gridAlpha = 0.1;
categoryAxis.axisAlpha = 0;
// Value
var valueAxis = new AmCharts.ValueAxis();
valueAxis.axisAlpha = 0;
valueAxis.gridAlpha = 0.1;
valueAxis.position = "top";
chart.addValueAxis(valueAxis);
// GRAPHS
// first graph
var graph1 = new AmCharts.AmGraph();
graph1.type = "column";
graph1.title = "This Week";
graph1.valueField = "This Week";
graph1.balloonText = "This Week:[[value]]";
graph1.lineAlpha = 0;
graph1.fillColors = "#ADD981";
graph1.fillAlphas = 1;
chart.addGraph(graph1);
// second graph
var graph2 = new AmCharts.AmGraph();
graph2.type = "column";
graph2.title = "Last Week";
graph2.valueField = "Last Week";
graph2.balloonText = "Last Week:[[value]]";
graph2.lineAlpha = 0;
graph2.fillColors = "#81acd9";
graph2.fillAlphas = 1;
chart.addGraph(graph2);
// Third graph
var graph3 = new AmCharts.AmGraph();
graph3.type = "column";
graph3.title = "2 Weeks Ago";
graph3.valueField = "2 Weeks Ago";
graph3.balloonText = "2 Weeks Ago:[[value]]";
graph3.lineAlpha = 0;
graph3.fillColors = "#9972C1";
graph3.fillAlphas = 1;
chart.addGraph(graph3);
// LEGEND
var legend = new AmCharts.AmLegend();
chart.addLegend(legend);
chart.creditsPosition = "top-right";
// WRITE
chart.write("chartdiv");
});
</script>
<script src="http://www.click-and-fit.me/amcharts_3.13.1.free/amcharts/serial.js"></script>
<script src="http://click-and-fit.me/amcharts_3.13.1.free/amcharts/amcharts.js"></script>
<body>
<div id="chartdiv" style="width:500px; height:600px;"></div>
</body>
These are the 2 files above in action:
http://click-and-fit.me/barClustered.php
Statistics Chart
Here's a screenshot of the 3 rows from the database I would like to show in the chart:
http://www.codingforums.com/redirect-to/?redirect=http%3A%2F%2Fimgbox.com%2FHfD1PuTQ
Currently the chart is filled with manually inputted data in a JSON format. How do I get the JSON string from the php file to be manipluated within the cart data? tried to look all over amcharts documentation and could not still understand how to do it.
Thanks in advance!
Try the following:
Change
AmCharts.loadJSON = function("barClustered.php") {
if (window.XMLHttpRequest) {
var request = new XMLHttpRequest();
} else {
var request = new ActiveXObject('Microsoft.XMLHTTP');
}
request.open('GET', "barClustered.php", false);
request.send();
return eval(request.responseText);
};
to
AmCharts.loadJSON = function(url) {
if (window.XMLHttpRequest) {
var request = new XMLHttpRequest();
} else {
var request = new ActiveXObject('Microsoft.XMLHTTP');
}
request.open('GET', url, false);
request.send();
return eval(request.responseText);
};
Change
chart.dataProvider = chartData;
to
chart.dataProvider = AmCharts.loadJSON('http://click-and-fit.me/barClustered.php');
I am trying to generate column chart on click of a button.When I click on the button drawchart() is called but no chart is created on screen.I examined the function by using alerts and found that data.addRow(array1[i],array2[j]) doesnt execute.The both arrays contain values extracted from json
Also when I remove this button and call function drawChart() on page load,I can see that only chart is created but no columns are drawn to it as there are no values in both the arrays.Any kind of help is really appreciated.
My code
<script type="application/javascript">
function loadJSON()
{
alert("hello");
alert(category);
alert(subcat);
alert(subdem);
var data_file = "https://tc.api.tibco.com:43/TopOne/v1/"+category+"/"+subcat+"/"+subdem;
alert("abc")
var http_request = new XMLHttpRequest();
try{
// Opera 8.0+, Firefox, Chrome, Safari
alert("in try");
http_request = new XMLHttpRequest();
}catch (e){
// Internet Explorer Browsers
try{ alert("in try1");
http_request = new ActiveXObject("Msxml2.XMLHTTP");
}catch (e) {
try{ alert("in try2");
http_request = new ActiveXObject("Microsoft.XMLHTTP");
}catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
http_request.onreadystatechange = function(){
if(http_request.readyState ==1){ alert("1");}
if(http_request.readyState ==2){ alert("2");}
if(http_request.readyState ==3){ alert("3");}
if(http_request.readyState ==4){ alert("4");}
if (http_request.readyState == 4 )
{
// Javascript function JSON.parse to parse JSON data
var jsonObj = JSON.parse(http_request.responseText);
alert(http_request.responseText);
alert(jsonObj);
// jsonObj variable now contains the data structure and can
// be accessed as jsonObj.name and jsonObj.country.
//alert( jsonObj.Category.CategoryName);
//alert(jsonObj.Category.CategoryName.Demographies.DemographyName);
//document.getElementById("Country").innerHTML = jsonObj.country;
alert(jsonObj.Category[0].SubCategory[0].Demographies[0].Items[0].Name);
alert(jsonObj.Category[0].SubCategory[0].Demographies[0].Items[1].Name);
for(i = 0;i<10;i++)
{
array1[i] = jsonObj.Category[0].SubCategory[0].Demographies[0].Items[i].Name;
array2[i] = jsonObj.Category[0].SubCategory[0].Demographies[0].Items[i].SalesCount;
}
for(i=0;i<10;i++)
{
alert(array1[i]+" "+array2[i]);
}
}
}
http_request.open("GET", data_file, true);
http_request.setRequestHeader("accept","application/json");
http_request.send();
}
function drawChart(){
alert("hello");
var data = new google.visualization.DataTable();
data.addColumn('string', 'name');
data.addColumn('number', 'salescount');
alert("ggg");
for(i = 0; i < array1.length; i++)
data.addRow([array1[i], array2[i]]);
var options = {
title: "Movies",
width: 600,height:400
//hAxis: {title: 'Year', titleTextStyle: {color: 'red'}}
};
var chart = new google.visualization.ColumnChart(document.getElementById('lowerRightDiv'));
chart.draw(data, options);
}
function initialize(){
$("button.charts").click(function() {
drawChart();
});
}
google.setOnLoadCallback(initialize);
google.load("visualization", "1", {packages:["corechart"]});
</script>
My code for the created button are
<button class="charts" onclick="initialize();"style="left:400px;">Generate charts</button>