how to make google chart API work under asp.net PageRequestManger - google-visualization

I have a submit button and upon pressing the button I display a loading image and then draw table and then draw google chart.
code for google chart (this works - verified it standalone):
<script type="text/javascript" src="//www.google.com/jsapi"></script>
<script type='text/javascript'>
google.load('visualization', '1', { packages: ['corechart']});
</script>
<script type='text/javascript'>
function drawVisualization() {
var data = google.visualization.arrayToDataTable([
['Year', 'Austria', 'Belgium', 'Czech Republic', 'Finland', 'France', 'Germany'],
['ENG 2001', 1336060, 3817614, 974066, 1104797, 6651824, 15727003],
['ENGLISH 2002', 1538156, 3968305, 928875, 1151983, 5940129, 17356071],
['ENGLISH2003', 1576579, 4063225, 1063414, 1156441, 5714009, 16716049]
])
new google.visualization.ColumnChart(document.getElementById('visualization')).
draw(data, {title:'Yearly Coffee Consumption by Country',
width:1000, height:600,hAxis: {title: 'Year'}, isStacked:true}
);
}
//google.setOnLoadCallback(drawVisualization);
</script>
code for loading image when pressing a submit button
<script type="text/javascript">
// Get the instance of PageRequestManager.
var prm = Sys.WebForms.PageRequestManager.getInstance();
// Add initializeRequest and endRequest
prm.add_initializeRequest(prm_InitializeRequest);
prm.add_endRequest(prm_EndRequest);
// Called when async postback begins
function prm_InitializeRequest(sender, args) {
//Display the loading image
var panelProg = $get('divImage');
panelProg.style.display = '';
}
// Called when async postback ends
function prm_EndRequest(sender, args) {
//Hide the loading image
var panelProg = $get('divImage');
panelProg.style.display = 'none';
//sort the table once retrieved from datatable from server
$(document).ready(function () {
$("#table").dataTable({
"sScrollY": "400px",
"bPaginate": false
});
//draw google chart (doesnt work)
google.setOnLoadCallback(drawVisualization);
//or even doesnt work (assume comment out for google.setOnLoadCallback(drawVisualization);
drawVisualization();
});
}
</script>
my submit button is under update panel (to make partial-page refresh for loading image to show user that it's fetching data from server). with this code, i am able to show loading image and display table but not google chart. I am not sure how I can call google chart draw function to make google chart appear. I have looked at several posting but couldnt find anything that works for my case. I even tried google.load('visualization', '1', { packages: ['corechart'], "callback":drawVisualization}) but it didnt work. I am so lost at this point. what is the correct way to make google chart work under update panel/PageRequestManager? Thanks!

I don't think you need (or want) to use a document ready handler in your prm_EndRequest function. Try this instead:
function prm_EndRequest(sender, args) {
//Hide the loading image
var panelProg = $get('divImage');
panelProg.style.display = 'none';
//sort the table once retrieved from datatable from server
$("#table").dataTable({
"sScrollY": "400px",
"bPaginate": false
});
drawVisualization();
}
To make sure the Viz API code doesn't try to run before the API is finished loading, you should make sure to wrap whatever code you use to hook up the AJAX call to your button inside a callback from the google loader.

Related

Some NuxtJS images break upon reload

In my website I have a series of images that serve as nuxt links to game pages:
<template>
<NuxtLink :to="game.pageName">
<img :src="game.boxImage" :height="gamePanelHeight" class="elevation-4"
/></NuxtLink>
</template>
Each of those links draws its properties from a content markup file like this:
index: 3
boxImage: gameImages/box_image.png
title: game title
pageName: games/whatever
And they're loaded into the page like so:
<script>
export default {
async asyncData({ $content, params }) {
const games = await $content('games').sortBy('index', 'asc').fetch()
return { games }
},
}
</script>
Whenever I refresh this page. All of these images break until I navigate outside the page and come back. What's causing this issue and how do I fix it?
This is a static Nuxt application FYI. And it's being served through an AWS S3 bucket but I don't think that's what's causing this issue.
EDIT: Also the boxImage that's in gameImages/box_image.png is from the static folder.
asyncData is not a hook that is triggered upon reaching an URL or using a reload (F5), it is only triggered during navigation.
If you want it to work even after a reload, use the fetch() hook.
More info here: https://nuxtjs.org/docs/2.x/components-glossary/pages-fetch#options
Edit on how to write it with fetch()
<script>
export default {
data() {
return {
games: [],
}
},
async fetch() {
this.games = await this.$content('games').sortBy('index', 'asc').fetch()
},
}
</script>

Loading GPX files from AmazonS3 with Google-Maps-APIv3 only works locally, but not on a deployed site (Heroku)

I'm trying to apply Google Maps API (v3) on my site, which is deployed on Heroku.
The map is populated with a given GPX file, provided by JS/Ajax.
The GPX file is stored on AmazonS3.
( I don't think that it's matter, but note the the site is built with Django, and the GPX file is a FileField of the relevant model ).
It works very well locally (local ip), but the map is not loaded at the deployed site.
I couldn't track any related error on the server logs, e.g. wrong key, etc.
Following is the relevant code snippet:
<div id="map" style="width: 50%; height: 50%;"></div>
<script>
function loadGPXFileIntoGoogleMap(map, filename) {
$.ajax({url: filename,
dataType: "xml",
success: function(data) {
var parser = new GPXParser(data, map);
parser.setTrackColour("#ff0000"); // Set the track line colour
parser.setTrackWidth(5); // Set the track line width
parser.setMinTrackPointDelta(0.001); // Set the minimum distance between track points
parser.centerAndZoom(data);
parser.addTrackpointsToMap(); // Add the trackpoints
parser.addRoutepointsToMap(); // Add the routepoints
parser.addWaypointsToMap(); // Add the waypoints
}
});
}
function initMap() {
var mapOptions = {
zoom: 8,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map"), mapOptions);
loadGPXFileIntoGoogleMap(map, "{{ object.gpx_file.url }}");
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=...&callback=initMap"
async defer></script>
Here is the corresponding snapshots:
Following is the console log (Chrome), while on the deployed site:
Can you please assist me with that?
Is that a GoogleMaps API issue? an AmazonS3 issue? Other?
How can I make GoogleMaps work on the deployed site?
Thanks ahead,
Shahar

google chart obtaining position in select event listener

I have the following google chart:
var elms=xml.getElementsByTagName("overall")[0];
var avgs=elms.getElementsByTagName("average");
for(var i=0;i<avgs.length;i++){
chartArr[0][i+1]=avgs[i].getAttribute("name");
chartArr[1][i+1]=parseFloat(avgs[i].getAttribute("avg"));
}
var data = google.visualization.arrayToDataTable(chartArr);
var options = {
title: 'Average Club Rating',
is3D: true,
width:1200,
chartArea:{
width:800,
left:92
}
};
var chart = new google.visualization.ColumnChart(document.getElementById('averagechart'));
chart.draw(data, options);
google.visualization.events.addListener(chart, 'select', function() {
console.log(this.getPosition());
});
If you look, i first populate the charArr then i create and setup the google chart.
On the bottom, you'll see the addListener call. What I want is when that element is clicked, a custom url most likely from the chartArr is used and determines the endpoint location.
How do I get the position of the listener so i can grab the custom url which is going to be created.
I dont really sure to understand your request, but you can print the event with this method,
console.log(chart.getSelection());
Regards,

google chart Json response within 1 sec but still get timeout after 30 sec and no "pause on exception"

I've tested this code in various constellations and only one of the constellations is giving me an error that I can't track down yet. Maybe someone else with more google-visualization experience can see the problem. In this one case, get the json resonse, then I get a token error with no token identified in the error message and "paus on error" does not pause anywhere in my js nor in external js. Then, after 30 sec. my callback is indeed called but with the error set to timeout (error in query).
Here is the URL which you can also test without SSL
https://cio-services.eu/demoOe2/Api/Insight/GetESiteEuoChart/?viewFlag=1&eSiteKid=4b92d450-b29d-47c0-943b-00890f56caf2&periodMin=7200&keyProp=KW15
Here is my client js which works in several scenarios
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
var chartOptions = {
curveType: 'none',
//width: 1200,
height: 400,
vAxis: { maxValue: 10, title: 'kWh/4 (15 min)' },
hAxis: { title: 'Time' },
title: 'Live production log',
titlePosition: 'out',
titleTextStyle: { fontSize: 14, textIndent: 10 },
fontSize: 12
};
google.load("visualization", "1", { packages: ["corechart"] });
google.setOnLoadCallback(drawChart);
var _chart;
function drawChart() {
//GET GChart data
var query = new google.visualization.Query('https://cio-services.eu/demoOe2/Api/Insight/GetESiteEuoChart/?viewFlag=1&eSiteKid=4b92d450-b29d-47c0-943b-00890f56caf2&periodMin=7200&keyProp=KW15');
//set query parameters
//query.setQuery('select 1, 2');
query.send(drawTable);
}
function drawTable(response) {
//error checking
if (response.isError()) {
alert('Error in query: ' + response.getMessage() + '' + response.getDetailedMessage());
return;
}
//convert response to JSON string
var googleDataQuery = response.getDataTable().toJSON();
//Convert JSON to google Data table
var convertedData = new google.visualization.DataTable(googleDataQuery, 0.5);
//Initialize a specific data table sub set view and store into a variable
var view = new google.visualization.DataView(convertedData);
_chart.draw(view, chartOptions);
}
$(function () {
_chart = new google.visualization.LineChart(document.getElementById('chart_div'));
});
</script>
OK, there is a bit of magic going on here that requires attentive reading of the doc to understand.
https://developers.google.com/chart/interactive/docs/dev/implementing_data_source
JSON Response Format
The default response format is JSON if the request includes an "X-DataSource-Auth" header, and JSONP otherwise. Note that the Google chart client actually supports a modified version of JSON and JSONP; if you are using the Java or Python helper libraries, they will put out the proper code for you; if you are parsing responses by hand, see JSON Modifications below
What happens is:
if you supply a target domain that in any way differs (even a different port) from the home domain, then google-visualization decides to remove the "X-DataSource-Auth" header property and thereby triggers the client to expect jsonP instead of json. Apparently the RequestID is also always zero in these cases. In any case, this means that you cannot simply reuse APIs for CORS and non-CORS access.
Just take a look at the http request header going out. If the Host: and Referer: properties differ in any way, then instead of returning pure json, you return something like this:
string returnVal = "google.visualization.Query.setResponse(" + my-valid-pure-json + ")";
Details here: https://developers.google.com/chart/interactive/docs/dev/implementing_data_source?hl=en
GG

JavaScript not firing in .ASCX page

I know I am new to the .net world, so there are limitations to what I know and understand. I am using Sitecore, and Sitecore generates the .aspx pages behind the scenes, so I have no access to the source, what I do have access to is the .ascx which is the sublayout ... so i tried to put some javascript onto the layout ... and I read that I am allowed to this with tags, but when I run the program now, it is not firing. Anything I am missing, please advise. Thank you for your assistance.
<!-- Custom Feedback Code -->
<script type="text/javascript">
function showModal() {
var url = document.URL;
var popUp = 'http://local.meau.com/components/supportcenter/feedback.aspx?value=';
var site = popUp + url;
var runpopUp = 50;
if (runpopUp >= Math.random() * 100) {
$(document).ready(function () {
$.fancybox({
'width': 500,
'height': '55%',
'autoScale': false,
'transitionIn': 'none',
'transitionOut': 'none',
'type': 'iframe',
'href': site,
'showCloseButton': false,
'title': 'We Request your Feedback'
});
});
}
}
</script>
<!-- End of Custom Feedback Code -->
I would suggest to start by removing (commenting out) the randomization logic - to make sure that your code is working deterministically first. Next, what is done in your code - the anonymous function is added as $(document).ready event handler inside showModal function. Unless you call showModal before $(document).ready fires, your handler will never be executed. Therefore, #Maras's suggestion should work, assuming, of course, that jquery javascript is loaded into the page.