The google chart code doesnt work in ie 8(XP) - javascript

I am working on SugarCRM framework, I give a call to html file in an iframe. The iframe has google chart api called. It loads in all other web browsers but not with ie8
Please let me where I am going wrong
<html>
<head>
<script type='text/javascript' src='https://www.google.com/jsapi'></script>
<script type='text/javascript' src="sample.js"></script>
<script type='text/javascript'>
//document.write("hi");
var or=window.location.href;
//alert(or);
var or1=or.split("=");
var id=or1[1];
//alert(id);
google.load('visualization', '1', {packages:['corechart']});
google.load("visualization", "1.0", {packages:["imagechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
// var jsona=<?php echo $jsonarr; ?>;
var jsona = $.ajax({
url:"index.php?entryPoint=surveychart&id="+id+"&mode=1",
dataType:"array",
async:false
}).responseText;
var some= eval('(' + jsona + ')');
//alert(jsona);
var data = google.visualization.arrayToDataTable(some);
var options = {
title: 'Survey Result',
hAxis: {title: 'Questions', titleTextStyle: {color: 'red'}}
};
var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
chart.draw(data, options);
google.visualization.events.addListener(chart, 'select',
function() {
var selection = chart.getSelection();
var message = '';
for (var i = 0; i < selection.length; i++) {
var item = selection[i];
if (item.row != null && item.column != null) {
var str = data.getFormattedValue(item.row, item.column);
message += '{row:' + item.row + ',column:' + item.column + '} = ' + str + '\n';
} else if (item.row != null) {
var str = data.getFormattedValue(item.row, 0);
message += '{row:' + item.row + ', column:none}; value (col 0) = ' + str + '\n';
} else if (item.column != null) {
var str = data.getFormattedValue(0, item.column);
message += '{row:none, column:' + item.column + '}; value (row 0) = ' + str + '\n';
}
}
if (message == '') {
message = 'nothing';
}
//alert('You selected ' + message);
var dataTable = new google.visualization.DataTable();
dataTable.addColumn('string');
dataTable.addColumn('number');
var dataTable1 = new google.visualization.DataTable();
dataTable1.addColumn('string');
dataTable1.addColumn('number');
var jsonage = $.ajax({
url:"index.php?entryPoint=surveychart&id="+id+"&mode=2&col="+item.column+"&row="+item.row,
dataType:"array",
async:false
}).responseText;
//alert(jsonage);
var jsongen = $.ajax({
url:"index.php?entryPoint=surveychart&id="+id+"&mode=3&col="+item.column+"& row="+item.row,
dataType:"array",
async:false
}).responseText;
var someage= eval('(' + jsonage + ')');
var somegen= eval('(' + jsongen + ')');
// alert(somegen);
dataTable.addRows(someage);
dataTable1.addRows(somegen);
var options1 = {cht: 'p', title: 'Answer By Age', chp: 0.628, chs: '400x200',
colors:['#3399CC','#00FF00','#0000FF']};
var options2 = {cht: 'p', title: 'Answer By Gender', chp: 0.628, chs: '400x200',
colors:['#3399CC','#00FF00','#0000FF']};
if(str!='')
{
var chart1 = new google.visualization.ImageChart(document.getElementById('pie_div'));
chart1.draw(dataTable, options1);
var chart2 = new google.visualization.ImageChart(document.getElementById('pie_div1'));
chart2.draw(dataTable1, options2);
}
}
);
}
</script>
</head>
<body>
<table><tr><td><div id='chart_div' style='width: 400px; height: 400px;'></div> </td></tr><tr><td><div id='pie_div' style='width: 400px; height:200px;' ></div> </td><td><div id='pie_div1' style='width: 400px; height: 200px;'></div></td></tr></table>
</body>
</html>

Related

Failed to parse Json into Html via JavaScript

I have the following JavaScript function that is called onload of an HTML page, but my data isn't parsing nor anything can be written in html through this function:
function displaySearchResults(){
//link base para a realização de requests para a API
var requestBaseURL = "https://api.predicthq.com/v1/events?";
var startDate = "start.gte=" + sessionStorage.getItem("startDate") + "&";
var endDate = "start.lte=" + sessionStorage.getItem("endDate") + "&";
var eventType = "category=" + sessionStorage.getItem("eventType") + "&";
var countrySearch = "country=" + sessionStorage.getItem("countrySearch");
var requestURL = requestBaseURL + startDate + endDate + eventType + countrySearch;
var searchRequest = new XMLHttpRequest();
searchRequest.withCredentials = false;
searchRequest.addEventListener("readystatechange", function () {
if (this.readyState === this.DONE) {
var data = JSON.parse(this.responseText);
console.log(data);
//TODO parse data into lists with associated buttons
var result = data.results
var msg = ""
for (var i=0;i < result.length;i++) {
msg += ("<li>" + result[i].title + "</li>\n");
}
msg = "<li>END</li>"
document.getElementsById("searchResults").innerHTML=msg;
}
});
}
Nor any data from the request nor de END msg is passing to the this HTML page:
(...)
<script type="text/javascript" src="js/script.js"></script>
</head>
<body onload="displaySearchResults()">
<header id="header">
</header>
<div class="container">
<div class="row">
<h5>Resultados:</h5>
<ul id="searchResults">
</ul>
</div>
</div>
</body>
Ive tried calling it at the end and after the body tag, same result. If its on load why doesn't appear anything, also console shows no errors.
Try this. It has a button which on click render the List in dom.
var data = {
results: [{
title: "title1"
}, {
title: "title2"
}, {
title: "title3"
}]
}
function LoadResult() {
var result = data.results
var msg = "<ul>"
result.forEach(s => {
msg = msg + "<li>" + s.title + "</li>"
})
msg = msg + "<li>END</li></ul>"
document.getElementById("result").innerHTML = msg;
}
<html>
<body>
<button onClick="LoadResult()">Load</button>
<div id="result">
</div>
</body>
</html>

Country name converter to ISO

I am trying to make a World chart that also shows how many transactions are coming from certain country's. But i need to translate the name of the country's to ISO because that is the only way this chart will work. Also the transactions is String (It is actually type of transactions) so i am trying to kind of convert the strings to numbers as well. I don't know if i am doing that right as well.
Here is my code:
<script>
var xmlURL = "some url";
var xml;
var xmlData;
var countryCodeColumn = "Counterparty country";
var categoryColumn = "Type of transaction";
var map;
var jsonText = "{";
var mapData;
var regionStyling = {initial: {fill: '#93959b'}};
$j.ajax({
url:xmlURL,
dataType:"xml",
beforeSend: function(){
$j('#loader').show();
},
success: function(data){
xml = data;
drawMap();
$j('#loader').hide();
}
});
function drawMap(){
console.log("xml as text", (new XMLSerializer()).serializeToString(xml));
var columns = {};
var columnNames = [];
var xmlColumns = $j('head', xml);
xmlColumns.find('headColumn').each(function(){
var columnName = $j(this).find('columnValue').text();
var columnID = $j(this).attr('columnid');
columns[columnName] = columnID;
console.log("column",columnName,columnID);
});
var xmlData = $j('data', xml);
var countryCode;
var category;
var categoryColor;
var url;
xmlData.find('item').each(function(){
itemId = $j(this).find('itemID').text();
url = "./injectColumnViewItemPage.action?metaData.channelID=9&metaData.siteID=723&metaData.sheetId=4640&metaData.itemId=" + itemId + "&metaData.sheetViewID=0&metaData.viewMode=0&view=readonly&sheetItemLinkView=true";
console.log("url", url);
console.log("itemid", itemId);
$j(this).find('column').each(function(){
var colID = $j(this).attr("columnid");
console.log(colID);
var value = $j(this).find('displayData').text();
console.log("field:", colID,value);
if(colID == columns[countryCodeColumn]){
countryCode = value;
}else if(colID == columns[categoryColumn]){
if(value != 0){
category++;
}
category = value;
categoryColor = $j(this).find('rawData').find('choice').attr('style');
}
});
jsonText += '"' + countryCode + '":{' + '"Transactions":"' + category + '","Color":"' + categoryColor + '","ItemID":' + itemId + '},';
});
jsonText = jsonText.substring(0,jsonText.length-1) + "}";
console.log("jsontext", jsonText);
mapData = JSON.parse(jsonText);
console.log("json", JSON.stringify(mapData));
map = new jvm.Map({container: $j('#isheet-map'),
map: 'world_mill_en',
series:{
regions: [{
normalizeFunction: 'polynomial'
}]
},
zoomOnScroll: true,
regionStyle: regionStyling,
backgroundColor: "#ffffff",
onRegionTipShow: function(e,el,code)
{
if(mapData[code])
{
el.html('<div style = "line-height:50%;"><span class="map-tip-title">' + el.html() + '</span><p></p><span class="map-tip-label">Transactions:</span>' + mapData[code]["Transactions"] + '<p></p></div>');
}else{
return false;
}
},
onRegionClick: function(e, code){
if(mapData[code]){
var href ="./injectColumnViewItemPage.action?metaData.channelID=9&metaData.siteID=" + 723 + "&metaData.sheetId=" + 4640 + "&metaData.itemId=" + mapData[code]["itemId"] + "&metaData.sheetViewID=0&metaData.viewMode=0&view=readonly&sheetItemLinkView=true";
$j("#iframe-Map").attr('src', href);
$j("#map-dialog").dialog({modal: true, title: map.getRegionName(code), width:600, height:500});
}
else{
return false;
}
}
});
map.series.regions[0].setValues(getColors());
function getColors(){
var colors = {};
$j.each(mapData,function(code,val){
colors[code] = mapData[code]["Color"];
});
console.log("colors", colors);
return colors;
}
}
</script>
There is nothing wrong with my ajax code since if i link it to another url it works fine

Google Visualization : How to call and draw sequential query with table?

I have to draw a side by side table with 2 different sql query data. I am sending in the given below format. However, it was drawn first query data into second table container instead with first table container.
var sqlQuery = "sql?tq=select Section, SubSection, Id, Question, Answer, Others where " +
"SubSection = '1.1' &sqlQueryID=questions_bank";
var query1 = new google.visualization.Query(sqlQuery);
TABLE_LOCATION = 'tableProductDeploymentContainer';
query1.send(drawQuestions);
var sqlQuery = "sql?tq=select Section, SubSection, Id, Question, Answer, Others where " +
"SubSection = '1.2' &sqlQueryID=questions_bank";
var query2 = new google.visualization.Query(sqlQuery);
TABLE_LOCATION = 'tableProductDeploymentContainer';
query2.send(drawQuestions);
break;
function drawQuestions(queryResponse) {
if (queryResponse.isError()) {
alert('Error in query: ' + queryResponseData.getMessage() + ' ' + queryResponseData.getDetailedMessage());
return;
}
var questionBankResponse = queryResponse.getDataTable();
if (questionBankResponse === null) {
alert('Empty rows in query: ' + questionBankResponse.getNumberOfRows());
return;
}
var questionDataTable = new google.visualization.DataTable();
questionDataTable.addColumn('string', '');
questionDataTable.addColumn('string', '');
questionDataTable.addColumn('string', '');
var questionDataTableRow = new Array();
var rowCounter;
for (rowCounter = 0; rowCounter < questionBankResponse.getNumberOfRows() ; rowCounter++) {
var count = 0 * 1;
var chbQuestion;
var questionId = questionBankResponse.getValue(rowCounter, 2);
var questionName = questionBankResponse.getValue(rowCounter, 3);
var answerValue = questionBankResponse.getValue(rowCounter, 4);
var answerOthers = questionBankResponse.getValue(rowCounter, 5);
if (answerOthers !== null)
answerOthers = answerOthers.toString();
if (answerValue === null)
answerValue = 0;
if (answerValue.toString() === "1")
chbQuestion = "<input type=\"checkbox\"" + " id=\"" + questionId + "\"" + " checked />";
else
chbQuestion = "<input type=\"checkbox\"" + " id=\"" + questionId + "\"" + " />";
questionDataTableRow[count++] = chbQuestion;
questionDataTableRow[count++] = questionName;
questionDataTableRow[count++] = answerOthers;
questionDataTable.addRow(questionDataTableRow);
}
var tableObject = new google.visualization.Table(document.getElementById(TABLE_LOCATION));
tableObject.draw(questionDataTable, { allowHtml: true, 'cssClassNames': cssClasses, width: '100%', sort: 'disable' });
}
I believe, there is some error in setting the TABLE_LOCATION global variable. Is there any way to pass the table container dynamically without maintaining in the global level.
Thanks for your help.
since the callback for Query.send is called asynchronously,
cannot guarantee one finishes before the other
as you point out, send the table id within the callback, rather than using global scope...
see following snippet...
var sqlQuery = "sql?tq=select Section, SubSection, Id, Question, Answer, Others where " +
"SubSection = '1.1' &sqlQueryID=questions_bank";
var query1 = new google.visualization.Query(sqlQuery);
query1.send(function (queryResponse) {
drawQuestions(queryResponse, 'tableProductDeploymentContainer');
});
var sqlQuery2 = "sql?tq=select Section, SubSection, Id, Question, Answer, Others where " +
"SubSection = '1.2' &sqlQueryID=questions_bank";
var query2 = new google.visualization.Query(sqlQuery2);
query2.send(function (queryResponse) {
drawQuestions(queryResponse, 'tableProductDeploymentContainer2');
});
function drawQuestions(queryResponse, TABLE_LOCATION) {
if (queryResponse.isError()) {
alert('Error in query: ' + queryResponseData.getMessage() + ' ' + queryResponseData.getDetailedMessage());
return;
}
var questionBankResponse = queryResponse.getDataTable();
if (questionBankResponse === null) {
alert('Empty rows in query: ' + questionBankResponse.getNumberOfRows());
return;
}
var questionDataTable = new google.visualization.DataTable();
questionDataTable.addColumn('string', '');
questionDataTable.addColumn('string', '');
questionDataTable.addColumn('string', '');
var questionDataTableRow = new Array();
var rowCounter;
for (rowCounter = 0; rowCounter < questionBankResponse.getNumberOfRows() ; rowCounter++) {
var count = 0 * 1;
var chbQuestion;
var questionId = questionBankResponse.getValue(rowCounter, 2);
var questionName = questionBankResponse.getValue(rowCounter, 3);
var answerValue = questionBankResponse.getValue(rowCounter, 4);
var answerOthers = questionBankResponse.getValue(rowCounter, 5);
if (answerOthers !== null)
answerOthers = answerOthers.toString();
if (answerValue === null)
answerValue = 0;
if (answerValue.toString() === "1")
chbQuestion = "<input type=\"checkbox\"" + " id=\"" + questionId + "\"" + " checked />";
else
chbQuestion = "<input type=\"checkbox\"" + " id=\"" + questionId + "\"" + " />";
questionDataTableRow[count++] = chbQuestion;
questionDataTableRow[count++] = questionName;
questionDataTableRow[count++] = answerOthers;
questionDataTable.addRow(questionDataTableRow);
}
var tableObject = new google.visualization.Table(document.getElementById(TABLE_LOCATION));
tableObject.draw(questionDataTable, { allowHtml: true, 'cssClassNames': cssClasses, width: '100%', sort: 'disable' });
}

Browser keeps loading after using ajax function with json

I've made a simple script which displays weather data by using Openweathermap. My current issues is that the loading indicator keeps on spinning around and I can't seem to fix it.
<html>
<head>
<title>Weather</title>
<meta charset="utf-8">
<script src="http://code.jquery.com/jquery-1.7.min.js" ></script>
<script src="http://code.jquery.com/ui/1.7.0/jquery-ui.js" ></script>
<script>
function getWeather(callback) {
var weather = 'http://api.openweathermap.org/data/2.5/weather?q=amsterdam&units=metric';
$.ajax({
dataType: "jsonp",
url: weather,
success: callback
});
}
getWeather(function (data) {
// Plaats
document.write('Current weather in ' + data.name);
document.write('<br> <br>');
// Icon
document.write("<img src=\"http://openweathermap.org/img/w/" + data.weather[0].icon + ".png\">");
document.write('<br>');
//Temp
var temp = (data.main.temp);
var fixed = (temp.toFixed(1));
document.write('Temperature: ' + fixed + '°C');
document.write('<br>');
// Pressure
document.write('Pressure: ' + data.main.pressure + ' Pa');
document.write('<br>');
// Humidity
document.write('Humidity: ' + data.main.humidity + '%');
document.write('<br>');
// Wind
document.write('Wind: ' + data.wind.speed + ' km/h');
document.write('<br>');
// Wind richting 1
var wind1 = (data.wind.deg)
var degrees = (wind1.toFixed(0))
s=String;
s.prototype.r = s.prototype.replace;
function calcPoint(input) {
var j = input % 8,
input = (input / 8)|0 % 4,
cardinal = ['north', 'east', 'south', 'west'],
pointDesc = ['1', '1 by 2', '1-C', 'C by 1', 'C', 'C by 2', '2-C', '2 by 1'],
str1, str2, strC;
str1 = cardinal[input];
str2 = cardinal[(input + 1) % 4];
strC = (str1 == cardinal[0] | str1 == cardinal[2]) ? str1 + str2 : str2 + str1;
return pointDesc[j].r(1, str1).r(2, str2).r('C', strC);
}
function getShortName(name) {
return name.r(/north/g, "N").r(/east/g, "E").r(/south/g, "S").r(/west/g, "W").r(/by/g, "b").r(/[\s-]/g, "");
}
var input = degrees / 11.25;
input = input+.5|0;
var name = calcPoint(input);
var shortName = getShortName(name);
name = name[0].toUpperCase() + name.slice(1);
document.write(name);
// Wind richting degress
var windfixed = (wind1.toFixed(0))
document.write('; '+ windfixed + '°');
document.write('<br>');
// Descriptie
document.write(data.weather[0].description);
document.write('<br>');
//tijd
var utcSeconds = (data.dt)
var d = new Date(0);
d.setUTCSeconds(utcSeconds);
document.write('<br>' + d);
document.write('<br>');
});
</script>
</body>
</html>
I think it's something with the callback but I'm not sure and my knowledge is not that big.
As I mentioned in my comment, it's because of the document.write() calls vs. when your ajax callback is triggered. Generally speaking, you should never use document.write(). You need to change it to append to update an existing element or create and append a DOM element.
One example: I added a div and I put all of the content in a variable and then updated the content of the div.
<html>
<head>
<title>Weather</title>
<meta charset="utf-8">
<script src="http://code.jquery.com/jquery-1.7.min.js" ></script>
<script src="http://code.jquery.com/ui/1.7.0/jquery-ui.js" ></script>
</head>
<body>
<div id='weather'></div>
<script>
function getWeather(callback) {
var weather = 'http://api.openweathermap.org/data/2.5/weather?q=amsterdam&units=metric';
$.ajax({
dataType: "jsonp",
url: weather,
success: callback
});
}
getWeather(function (data) {
var weatherContent='';
// Plaats
weatherContent+='Current weather in ' + data.name;
weatherContent+='<br> <br>';
// Icon
weatherContent+="<img src=\"http://openweathermap.org/img/w/" + data.weather[0].icon + ".png\">";
weatherContent+='<br>';
//Temp
var temp = (data.main.temp);
var fixed = (temp.toFixed(1));
weatherContent+='Temperature: ' + fixed + '°C';
weatherContent+='<br>';
// Pressure
weatherContent+='Pressure: ' + data.main.pressure + ' Pa';
weatherContent+='<br>';
// Humidity
weatherContent+='Humidity: ' + data.main.humidity + '%';
weatherContent+='<br>';
// Wind
weatherContent+='Wind: ' + data.wind.speed + ' km/h';
weatherContent+='<br>';
// Wind richting 1
var wind1 = (data.wind.deg)
var degrees = (wind1.toFixed(0))
s=String;
s.prototype.r = s.prototype.replace;
function calcPoint(input) {
var j = input % 8,
input = (input / 8)|0 % 4,
cardinal = ['north', 'east', 'south', 'west'],
pointDesc = ['1', '1 by 2', '1-C', 'C by 1', 'C', 'C by 2', '2-C', '2 by 1'],
str1, str2, strC;
str1 = cardinal[input];
str2 = cardinal[(input + 1) % 4];
strC = (str1 == cardinal[0] | str1 == cardinal[2]) ? str1 + str2 : str2 + str1;
return pointDesc[j].r(1, str1).r(2, str2).r('C', strC);
}
function getShortName(name) {
return name.r(/north/g, "N").r(/east/g, "E").r(/south/g, "S").r(/west/g, "W").r(/by/g, "b").r(/[\s-]/g, "");
}
var input = degrees / 11.25;
input = input+.5|0;
var name = calcPoint(input);
var shortName = getShortName(name);
name = name[0].toUpperCase() + name.slice(1);
weatherContent+=name;
// Wind richting degress
var windfixed = (wind1.toFixed(0))
weatherContent+='; '+ windfixed + '°';
weatherContent+='<br>';
// Descriptie
weatherContent+=data.weather[0].description;
weatherContent+='<br>';
//tijd
var utcSeconds = (data.dt)
var d = new Date(0);
d.setUTCSeconds(utcSeconds);
weatherContent+='<br>' + d;
weatherContent+='<br>';
document.getElementById('weather').innerHTML=weatherContent;
});
</script>
</body>
</html>
Use this code. This will help you.
function getWeather(callback) {
var weather = 'http://api.openweathermap.org/data/2.5/weather?q=amsterdam&units=metric';
$.ajax({
dataType: "jsonp",
url: weather,
success: callback
});
}
getWeather(callback1);
function callback1(data)
{
// Plaats
document.write('Current weather in ' + data.name);
document.write('<br> <br>');
// Icon
document.write("<img src=\"http://openweathermap.org/img/w/" + data.weather[0].icon + ".png\">");
document.write('<br>');
//Temp
var temp = (data.main.temp);
var fixed = (temp.toFixed(1));
document.write('Temperature: ' + fixed + '°C');
document.write('<br>');
// Pressure
document.write('Pressure: ' + data.main.pressure + ' Pa');
document.write('<br>');
// Humidity
document.write('Humidity: ' + data.main.humidity + '%');
document.write('<br>');
// Wind
document.write('Wind: ' + data.wind.speed + ' km/h');
document.write('<br>');
// Wind richting 1
var wind1 = (data.wind.deg)
var degrees = (wind1.toFixed(0))
s=String;
s.prototype.r = s.prototype.replace;
var input = degrees / 11.25;
input = input+.5|0;
var name = calcPoint(input);
var shortName = getShortName(name);
name = name[0].toUpperCase() + name.slice(1);
document.write(name);
// Wind richting degress
var windfixed = (wind1.toFixed(0))
document.write('; '+ windfixed + '°');
document.write('<br>');
// Descriptie
document.write(data.weather[0].description);
document.write('<br>');
//tijd
var utcSeconds = (data.dt)
var d = new Date(0);
d.setUTCSeconds(utcSeconds);
document.write('<br>' + d);
document.write('<br>');
return;
}
function calcPoint(input) {
var j = input % 8,
input = (input / 8)|0 % 4,
cardinal = ['north', 'east', 'south', 'west'],
pointDesc = ['1', '1 by 2', '1-C', 'C by 1', 'C', 'C by 2', '2-C', '2 by 1'],
str1, str2, strC;
str1 = cardinal[input];
str2 = cardinal[(input + 1) % 4];
strC = (str1 == cardinal[0] | str1 == cardinal[2]) ? str1 + str2 : str2 + str1;
return pointDesc[j].r(1, str1).r(2, str2).r('C', strC);
}
function getShortName(name) {
return name.r(/north/g, "N").r(/east/g, "E").r(/south/g, "S").r(/west/g, "W").r(/by/g, "b").r(/[\s-]/g, "");
}`
Firstly, avoid use of document.write. it cause anoying problems sometimes.
instead use document.write append every code to an output var and at the end, put it's content on the page inside a div
I've change your code and place the function call inside a $(function(){}) if don't use it, the code will be executed before target div () exists, and it will thrown an error
plus, you forgot to open
<html>
<head>
<title>Weather</title>
<meta charset="utf-8">
<script src="http://code.jquery.com/jquery-1.7.min.js" ></script>
<script src="http://code.jquery.com/ui/1.7.0/jquery-ui.js" ></script>
<script>
function getWeather(callback) {
var weather = 'http://api.openweathermap.org/data/2.5/weather?q=amsterdam&units=metric';
$.ajax({
dataType: "jsonp",
url: weather,
success: callback
});
}
$(function(){
getWeather(function (data) {
var output = '';
// Plaats
output += 'Current weather in ' + data.name;
output += '<br> <br>';
// Icon
output += "<img src=\"http://openweathermap.org/img/w/" + data.weather[0].icon + ".png\">";
output += '<br>';
//Temp
var temp = (data.main.temp);
var fixed = (temp.toFixed(1));
output += 'Temperature: ' + fixed + '°C';
output += '<br>';
// Pressure
output += 'Pressure: ' + data.main.pressure + ' Pa';
output += '<br>';
// Humidity
output += 'Humidity: ' + data.main.humidity + '%';
output += '<br>';
// Wind
output += 'Wind: ' + data.wind.speed + ' km/h';
output += '<br>';
// Wind richting 1
var wind1 = (data.wind.deg)
var degrees = (wind1.toFixed(0))
s=String;
s.prototype.r = s.prototype.replace;
function calcPoint(input) {
var j = input % 8,
input = (input / 8)|0 % 4,
cardinal = ['north', 'east', 'south', 'west'],
pointDesc = ['1', '1 by 2', '1-C', 'C by 1', 'C', 'C by 2', '2-C', '2 by 1'],
str1, str2, strC;
str1 = cardinal[input];
str2 = cardinal[(input + 1) % 4];
strC = (str1 == cardinal[0] | str1 == cardinal[2]) ? str1 + str2 : str2 + str1;
return pointDesc[j].r(1, str1).r(2, str2).r('C', strC);
}
function getShortName(name) {
return name.r(/north/g, "N").r(/east/g, "E").r(/south/g, "S").r(/west/g, "W").r(/by/g, "b").r(/[\s-]/g, "");
}
var input = degrees / 11.25;
input = input+.5|0;
var name = calcPoint(input);
var shortName = getShortName(name);
name = name[0].toUpperCase() + name.slice(1);
output += name;
// Wind richting degress
var windfixed = (wind1.toFixed(0))
output += '; '+ windfixed + '°';
output += '<br>';
// Descriptie
output += data.weather[0].description;
output += '<br>';
//tijd
var utcSeconds = (data.dt)
var d = new Date(0);
d.setUTCSeconds(utcSeconds);
output += '<br>' + d;
output += '<br>';
document.getElementById('output-div').innerHTML = output ;
});
})
</script>
<body>
<div id="output-div"></div>
</body>
</html>
<html>
<head>
<title>Weather</title>
<meta charset="utf-8">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
</head>
<body>
<div class="container">
<div id="weather-location"></div>
<div id="weather-icon"></div>
<div id="weather-temp"></div>
<div id="weather-pressure"></div>
<div id="weather-humidity"></div>
<div id="weather-wind"></div>
<div id="weather-wind-direction"></div>
<div id="weather-description"></div>
<div id="weather-time"></div>
</div>
<script>
$(document).ready(function(){
$.ajax({
dataType: "jsonp",
url: "http://api.openweathermap.org/data/2.5/weather?q=amsterdam&units=metric",
success: function(data){
$("#weather-location").text('Current weather in ' + data.name);
// Icon
//$("#weather-icon").html("<img src='http://openweathermap.org/img/w/" + data.weather[0].icon + ".png'>");
//Temp
var temp = (data.main.temp);
var fixed = (temp.toFixed(1));
$("#weather-temp").text('Temperature: ' + fixed + '°C');
// Pressure
$("#weather-pressure").text('Pressure: ' + data.main.pressure + ' Pa');
// Humidity
$("#weather-humidity").text('Humidity: ' + data.main.humidity + '%');
// Wind
$("#weather-wind").text('Wind: ' + data.wind.speed + ' km/h');
// Wind richting 1
var wind1 = (data.wind.deg)
var degrees = (wind1.toFixed(0))
s=String;
s.prototype.r = s.prototype.replace;
function calcPoint(input) {
var j = input % 8,
input = (input / 8)|0 % 4,
cardinal = ['north', 'east', 'south', 'west'],
pointDesc = ['1', '1 by 2', '1-C', 'C by 1', 'C', 'C by 2', '2-C', '2 by 1'],
str1, str2, strC;
str1 = cardinal[input];
str2 = cardinal[(input + 1) % 4];
strC = (str1 == cardinal[0] | str1 == cardinal[2]) ? str1 + str2 : str2 + str1;
return pointDesc[j].r(1, str1).r(2, str2).r('C', strC);
}
function getShortName(name) {
return name.r(/north/g, "N").r(/east/g, "E").r(/south/g, "S").r(/west/g, "W").r(/by/g, "b").r(/[\s-]/g, "");
}
var input = degrees / 11.25;
input = input+.5|0;
var name = calcPoint(input);
var shortName = getShortName(name);
name = name[0].toUpperCase() + name.slice(1);
// Wind richting degress
var windfixed = (wind1.toFixed(0))
$("#weather-wind-direction").text(name + "; "+ windfixed + "°");
// Descriptie
$("#weather-description").text(data.weather[0].description);
//tijd
var utcSeconds = (data.dt)
var d = new Date(0);
d.setUTCSeconds(utcSeconds);
$("#weather-time").text(d);
},
fail: function(){
$(".container").html('<h1>FAIL!</h1>');
}
});
});
</script>
</body>
</html>

google visualization multiple charts with own data queries

On my Google Visualization web page I want both a bar chart and an area chart but I can get only one or the other to display.
Each chart requires its own data and employs its own google.visualization.Query object against my own Python-based server. My initialize function calls the function to display the first chart, and at the bottom of the query response handler for the first chart, I'm calling the function to display the second chart. (I am doing this to make sure my second data query does not start until after the first chart is done drawing.) Each chart displays correctly when I code to draw only one chart at a time. But when I try to draw both charts, only the first chart ever draws even though I am verifying that both data queries are running and returning valid json responses, at the correct times.
Thanks for any help, BH
Edit 10/27/2013:
This post solved my problem:
Google Charts - "Missing Query for request id: 0"
To anyone implementing a Python data source, parse the reqId parameter like this:
import cgi
form = cgi.FieldStorage()
tqx = form.getvalue("tqx") # tqx comes back like "reqId:1"
req_id = int(tqx[tqx.find("reqId"): ].split(":")[1])
And pass it to the ToJSonResponse call:
response = data_table.ToJSonResponse(req_id=req_id,
columns_order=("vehicle_id", "num_events"))
print "Content-type: text/plain"
print
print response
Here is my updated code, which also uses the "ready" event.
<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(initialize);
var timelineDate1 = "";
var messageCountsDate1 = "";
var timeline_drawn = false;
var message_count_drawn = false;
function initialize()
{
drawTimeline();
}
function drawTimeline()
{
var rows = QueryString.rows || "4";
var date1 = QueryString.date1 || "2013-9-1"; // Date start
timelineDate1 = date1;
var page = parseInt(QueryString.page) || 1;
if (page < 1)
{
page = 1;
}
// Timeline
var url_timeline = "http://localhost/emit_event_timeline.py"
+ "?date1=" + date1 + "&rows=" + rows + "&page=" + page;
var query_timeline = new google.visualization.Query(url_timeline);
query_timeline.setTimeout(14400);
query_timeline.send(handleTimelineQueryResponse);
}
function handleTimelineQueryResponse(response)
{
var stack = parseInt(QueryString.stack) || 1
var timeline_options =
{
title: 'Event Count Timeline, ' + timelineDate1 + ' to Present',
vAxis: {title: 'Date', titleTextStyle: {color: 'red'}},
hAxis: {title: 'Event Count', titleTextStyle: {color: 'blue'}},
isStacked: stack
};
if (response.isError())
{
alert('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
return;
}
var timeline_data_table = response.getDataTable();
var timeline_chart = new google.visualization.AreaChart(document.getElementById('timeline_div'));
google.visualization.events.addListener(timeline_chart, 'ready', timeline_chart_ready);
google.visualization.events.addListener(timeline_chart, 'error', errorHandler);
timeline_chart.draw(timeline_data_table, timeline_options);
}
function timeline_chart_ready()
{
timeline_drawn = true;
if (!message_count_drawn)
{
drawMessagecounts();
}
}
function mc_chart_ready()
{
message_count_drawn = true;
if (!timeline_drawn)
{
drawTimeline();
}
}
function drawMessagecounts()
{
var rows = QueryString.rows || "20";
var date1 = QueryString.date1 || "2013-9-1"; // Date start
messageCountsDate1 = date1
var page = parseInt(QueryString.page) || 1;
if (page < 1)
{
page = 1;
}
// Message counts
var url_message_counts = "http://localhost/emit_all_message_counts.py"
+ "?date1=" + date1 + "&page=" + page + "&rows=" + rows;
var query_message_counts = new google.visualization.Query(url_message_counts)
query_message_counts.setTimeout(14400);
query_message_counts.send(handleMessageCountQueryResponse);
}
function handleMessageCountQueryResponse(response)
{
var stack = parseInt(QueryString.stack) || 1
var mc_options =
{
title: 'Message Counts, ' + messageCountsDate1 + ' to Present',
vAxis: {title: 'Message Source', titleTextStyle: {color: 'red'}},
hAxis: {title: 'Message Count', titleTextStyle: {color: 'blue'}},
isStacked: stack
};
if (response.isError())
{
alert('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
return;
}
var mc_data_table = response.getDataTable();
var mc_chart = new google.visualization.BarChart(document.getElementById('message_count_div'));
google.visualization.events.addListener(mc_chart, 'ready', mc_chart_ready);
google.visualization.events.addListener(mc_chart, 'error', errorHandler);
mc_chart.draw(mc_data_table, mc_options);
}
// Thanks to:
// https://stackoverflow.com/questions/901115/how-can-i-get-query-string-values
var QueryString = function ()
{
// This function is anonymous, is executed immediately and
// the return value is assigned to QueryString!
var query_string = {};
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
// If first entry with this name
if (typeof query_string[pair[0]] === "undefined") {
query_string[pair[0]] = pair[1];
// If second entry with this name
} else if (typeof query_string[pair[0]] === "string") {
var arr = [ query_string[pair[0]], pair[1] ];
query_string[pair[0]] = arr;
// If third or later entry with this name
} else {
query_string[pair[0]].push(pair[1]);
}
}
return query_string;
} ();
function errorHandler(e)
{
// Called when an error occurs during chart processing
alert('Error handler: ' + e.message);
}
</script>
</head>
<body>
<div id="timeline_div" style="width:800px;height:500px;border:1px solid gray;float:left">
</div>
<div id="message_count_div" style="width:800px;height:500px;border:1px solid gray;float:left">
</div>
<div id="control_div" style="width:80px;height:60px;float:left">
</div>
</body>
</html>
The solution was for my Python data source to pass the reqId parameter from the request back on the json reqponse. This post solved my problem:
Google Charts - "Missing Query for request id: 0"

Categories

Resources