Loading Google Chart Api using Ajax in html page - html

I am using Ajax code to load the html page
for example:
$.ajax({
url: 'Context.html',
dataType: 'html',
timeout: 500,
success: function(html) {
$("div#mainbody").html(html);
}
});
The Context.html I am loading it in some other html page say Home.html
But I am generating pie charts using google API in Context.html
and the code for generating pie chart i.e in Context.html is
<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([
['Year', 'Count'],
['2005', 70],
['2006', 80],
['2007', 140],
['2008', 220],
['2009', 290],
['2010', 400],
['2011', 500]
]);
var options = {
title: 'Head Count-(Apple Year)',
colors:['#129212']
};
var chart = new google.visualization.ColumnChart(document.getElementById('jsf_headcount_bargraph'));
chart.draw(data, options);
}
</script>
When I am loading Context.html in Home.html page I cannot find the pie chart which is in Context.html after loading it in the Home.html
I tried by giving ALERT(""); in script where I wrote code for pie chart. I was getting alert message,so Ajax is executing javascript but I am not getting pie chart which is same script. So I was stucked with Loading pie chart in Home.html page

If you make Context.html like this
<script>
var j = 20;
alert();
</script>
Then I do get an alert (using $.ajax({success: function() {} }) etc. ).
[ Example ]
function execAjax() {
$.ajax( {
url: 'index2.html',
success: function( html ) {
$("#content").html( html );
checkJSvalue();
},
error: function() {
alert( "Error" );
}
});
}
function checkJSvalue() {
alert( j );
}
Example HTML (index2.html)
<div>
content of index2.html
</div>
<script>
var j = 20;
alert();
</script>
What I have tried to do is to put the code directly in the 'home.html' and I already got errors. You should reverse the order of usage and declaration of the drawchart function anyways.
// Bad
// google.setOnLoadCallback(drawChart);
// function drawChart() {}
// Good
function drawChart() {}
google.setOnLoadCallback(drawChart);
Other than that, I already got this error from the google.jsapi.js (copied locally)
Uncaught Error: Container is not defined format+nl,default,corechart.I.js:841
So something goes wrong there, that is not part of the actual question and it's minified etc. so I won't go there.
Hope this was helpful :)

Everything works just fine if i replace the code
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
To inline
google.load('visualization', '1.0', {'packages':['corechart'], "callback": drawChart});

Related

getting spreadsheet data to chart data array

Although I found similar posts elsewhere, I still cannot solve my issue.
I want to load locations on a html sidebar page on google spreadsheet, but the only example I find are hard-coded locations.
Here is an example, on HTML page (I removed API Key): this one works for me.
<body>
<div class="container">
<div id="map_div" style="width: 500px; height: 500px"></div>
</div> <!-- CLOSE CONTAINER -->
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.load("current", {
"packages":["map"],
"mapsApiKey": "xxxx"
});
google.charts.setOnLoadCallback(drawChart);
function drawChart(arrayToData) {
var data = new google.visualization.arrayToDataTable(
[["Lat", "Long","Nom"],
[45.7660889, 4.794056299999999, "Person1"],
[45.8167227, 4.8341048, "Person2"],
[45.7796433, 4.8037871, "Person3"],
[45.7780849, 4.921768399999999, "Person4"]]
);
var map = new google.visualization.Map(document.getElementById('map_div'));
map.draw(data, {
showTooltip: true,
showInfoWindow: true
});
}//function drawChart() {
</script>
</body>
And I would like to have something looking like that, where data locations are not hard-coded but comes from spreadsheet data :
google.charts.setOnLoadCallback(drawChart);
var ss = SpreadsheetApp.openByUrl("xxxx");
var datatable = ss.getRange("listNamesAdresses");
function drawChart(arrayToData) {
var dataToArray=document.getElementById("listNamesAdresses");
var data = new google.visualization.arrayToDataTable(
dataToArray
);
var map = new google.visualization.Map(document.getElementById('map_div'));
map.draw(data, {
showTooltip: true,
showInfoWindow: true
});
}//function drawChart() {
I'm aware this is not correct, but I tried many combinations, still cannot solve it. Your help is welcome !
Here is a sharable example of what I made :
Link to a copy of my Map Test
I adapted it from my spreadsheet but went out of my quota for my API key, so I could'nt test it yet. I hope this will be fine !
Many thanks in advance
EDIT 2 :
I followed ziganotschka's suggestions (thank you very much for your time) : I couldn't apply the HtmlCreateOutputFromFil("index.html") so I stuck to my code for displaying a sidepage Html. For the rest of it : I now have a map (first victory!).
But, it says : "no data points to show".
I checked on values return by getAddresses function, seems OK. For getting easier on it, I changed the function to an easier one : getGeoCodesAndNames. This one returns, as it says, geocode latitude, longitude, and name.
Here are my new code sample and link to the new version of the spreadsheet :
Gs-code :
function getGeoCodesAndNames(){
//get addresses and names list
var namesAddresses=ss.getRange("ListNamesAddresses");
var a_values=namesAddresses.getValues();
Logger.log(a_values);
/* returns
[[Lat, Lon, Name],
[45.7660889, 4.79405629999999, person1],
[45.8167227, 4.8341048, person2],
[45.7796433, 4.8037871, person3],
[45.7780849, 4.921768399999999, person4]]
*/
return a_values;
}//function getGeoCodesAndNames(){
function testMap2(){
var template = HtmlService.createTemplateFromFile("carte2");
var html = template.evaluate();
html.setTitle("Display Map 2").setHeight(550).setWidth(550);
SpreadsheetApp.getUi().showModalDialog(html, "Locations")
}//function testCarte1(){
and HTML code :
<script type="text/javascript">
window.onload = google.script.run.withSuccessHandler(onSuccess).getGeoCodesAndNames();
function onSuccess (arrayToData){
google.charts.load("current", {
"packages":["map"],
"mapsApiKey": "AIzaSyC4WPcWGMZRoqSAfZ0F4RzvWtN6Jy7hmdE"
});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable(arrayToData);
var map = new google.visualization.Map(document.getElementById('map_div'));
map.draw(data, {
showTooltip: true,
showInfoWindow: true
});
}// function drawChart() {
}//function onSuccess (arrayToData){
</script>
And here is the link to the new spreadsheet version :
TestMap2
Do I need to publish it as a web app if I just want to have a side page ? On previous projects I had, I could add datas from a side-page to a spreadsheet without it. In the oppposite ways, can you confirm I need to do it ? I tried, did not change anything on my current result : maybe I made something wrong.
Many thanks again for your help !
EDIT 3 :
I finally got it : My geocode/address function were not returning a proper format for coordinates, because of two things :
1) I'm using French typing, ie dot are replaced with commas in numbers
2) I had to add one more """ symbol at beginning and ending of each string part in the array.
Here is the correct function (might be improved, but..does the job):
function getGeoCodesAndNames(){
//get addresses and names list
var namesAddresses=ss.getRange("ListNamesAddresses");
var a_values=namesAddresses.getValues();
for (var i=0;i<a_values.length;i++){
for (var j=0;j<a_values[0].length;j++){
var value=a_values[i][j];
if (typeof value == "string"){
a_values[i][j]="\"" + value + "\"";
}
}
}
return a_values;
}//function getGeoCodesAndNames(){
Many thanks to the people who helped me !
To combine using the Visualization API in Javascript with retrieving spreadsheet data with Apps Script - you need to use a WebApp
Use google.script.run to pass data from the serverside to clientside
Sample:
code.gs
function doGet() {
return HtmlService.createHtmlOutputFromFile("index.html");
}
function getDatafromSheet(){
var ss = SpreadsheetApp.openByUrl("xxxx");
// getNamedRanges()[0] works if you have only one named range
var datatable = ss.getNamedRanges()[0].getRange().getValues();
return datatable;
}
index.html
<body>
<div class="container">
<div id="map_div" style="width: 500px; height: 500px"></div>
</div> <!-- CLOSE CONTAINER -->
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
window.onload = google.script.run.withSuccessHandler(onSuccess).getDatafromSheet();
function onSuccess (arrayToData){
google.charts.load("current", {
"packages":["map"],
"mapsApiKey": "AIzaSyDCKzjezYeUDd2ugtFnzokCIpV1YpLmmEc"
});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.arrayToDataTable(arrayToData);
var map = new google.visualization.Map(document.getElementById('map_div'));
map.draw(data, {
showTooltip: true,
showInfoWindow: true
});
}
}
</script>
</body>

Sharepoint How to change function of new document

I have a document library and whenever I click on the new document (https://imgur.com/a/X4ATVX2) it will show this(https://imgur.com/a/6ExJ0Lr) for me to upload a document. How do I change this, so that it will display this (https://imgur.com/a/2JZvPDc) instead? I want to create a new document set instead of uploading a document file. Please advise.
I've watch some guides on the internet, their new is at this position. (https://imgur.com/a/X4ATVX2)
Add the code below into script editor web part in list view page.
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script type="text/javascript">
jQuery(document).ready(function($){
var listTitle="Test600DL";
var rootFolder=_spPageContextInfo.webServerRelativeUrl+"/"+listTitle;
$.ajax({
url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('"+listTitle+"')/contenttypes?$select=StringId&$filter=Name eq 'Document Set'",
type: "GET",
headers: {
"Accept": "application/json;odata=verbose",
},
success: function (data) {
if(data.d.results.length>0){
var contentTypeId=data.d.results[0].StringId;
var urlString="ContentTypeId="+contentTypeId+"&RootFolder="+rootFolder;
var $newDocumentLink=$("a[id^='idHomePageNewDocument']");
$newDocumentLink.attr("onclick",$newDocumentLink.attr("onclick").replace("Upload.aspx","NewDocSet.aspx").replace("RootFolder=",urlString));
$newDocumentLink.attr("href",$newDocumentLink.attr("href").replace("Upload.aspx","NewDocSet.aspx").replace("RootFolder=",urlString));
}
},
error: function (data) {
//alert("Error");
}
});
});
</script>

How to make google chart using ajax and json in django?

I want to insert google chart using json file.
this is the one views.py function to load json file. =>
def get_addresses(request):
addresses = Address.objects.all().values('address', 'postalcode', 'country', 'latitude', 'longitude')
addresses_list = list(addresses)
return JsonResponse(addresses_list, safe=False)
and this is one of the example of json => [{"address": "\uc11c\uc6b8 \uac15\ub0a8\uad6c \uac1c\ud3ec2\ub3d9 ", "postalcode": "135993", "country": "Republic of Korea", "latitude": "37.4896011", "longitude": "127.0687685"}
I don't know why it doesn't show up google chart.
I got the address from google map api randomly generated. I think google chart could read the address which looks like a key or something.
So I don't think it's the problem of address.
Can anyone please tell what is the problem?
<html>
<head>
<script type="text/javascript"
src='https://www.gstatic.com/charts/loader.js'></script>
<script type='text/javascript' src='https://www.google.com/jsapi'>
</script>
<script type="text/javascript">
google.charts.load('current', {
'packages': ['geochart'],
// Note: you will need to get a mapsApiKey for your project.
// See:
'mapsApiKey': 'AIzaSyBZ20X5YvOthFtpf48PMJbCek6456cfSTM'
});
google.charts.setOnLoadCallback(drawMarkersMap);
function drawMarkersMap() {
var jsonData = $.ajax({
url: "senders_list.json",
dataType: "json",
async: false
}).responseText;
var data = google.visualization.arrayToDataTable(jsonData);
var options = {
region: 'KR',
displayMode: 'markers',
colorAxis: {colors: ['green', 'blue']}
};
var chart = new
google.visualization.GeoChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
</head>
<body>
<div id="chart_div" style="width: 900px; height: 500px;"></div>
</body>
</html>

Google Charts Does not render for a scatter plot with multiple colors

I am plotting up data in Google Charts and continue to have trouble rendering my HTML. I could sure use a second pair of eyes to check if there is anything obviously wrong with the code below. The data has three columns, each of which is meant to be plotted a different color.
<html>
<head>
<!--Load the AJAX API-->
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
// Load the Visualization API and the piechart package.
google.load("visualization", "1", {packages:["corechart"]});
// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(drawChart);
// Callback that creates and populates a data table,
// instantiates the pie chart, passes in the data and
// draws it.
function drawChart() {
// Create the data table.
var data = google.visualization.arrayToDataTable()({
[['x','Virg','Set','Versi'],
[1.0,null,null,1.0],
[2.0,null,2.0,null],
[3.0,3.0,null,null]]
});
// Set chart options
var options = {
title: "Edgar Anderson's Iris Data Set",
hAxis: {title: 'Petal Length', minValue: 0, maxValue: 7},
vAxis: {title: 'Petal Width', minValue: 0, maxValue: 2.5},
legend: ''
//series:{
// 0: { pointShape: 'circle' },
// 1: {pointShape: 'triangle'},
// 2: { pointShape: 'square'}
// }
};
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.ScatterChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
</head>
<body>
<!--Div that will hold the pie chart-->
<div id="chart_div" style="width: 900px; height: 500px;"></div>
</body>
</html>
Call to arrayToDataTable() is wrong. Instead of
var data = google.visualization.arrayToDataTable()({
[['x','Virg','Set','Versi'],
[1.0,null,null,1.0],
[2.0,null,2.0,null],
[3.0,3.0,null,null]]
});
you have to use
var data = google.visualization.arrayToDataTable([
['x','Virg','Set','Versi'],
[1.0,null,null,1.0],
[2.0,null,2.0,null],
[3.0,3.0,null,null]
]);
Instead of an object of array you have to provide an array of arrays. And unnecessary () deleted.
**Update: ** example at jsbin.

Update Google Chart in real time with comet

I want to use Google Chart to create a bar chart that gets updated in realtime.
When the user loads the page, I want to show the current results. But as soon as the data in my database changes, I would like to push these changes to the client and update the graph.
Here is a bar chart example from the Google Charts page:
<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 = new google.visualization.DataTable();
data.addColumn('string', 'Year');
data.addColumn('number', 'Sales');
data.addColumn('number', 'Expenses');
data.addRows([
['2004', 1000, 400],
['2005', 1170, 460],
['2006', 660, 1120],
['2007', 1030, 540]
]);
var options = {
title: 'Company Performance',
vAxis: {title: 'Year', titleTextStyle: {color: 'red'}}
};
var chart = new google.visualization.BarChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
I guess I could use an Ajax-Request to pull the data every some seconds and redraw the chart. But maybe there is some inbuild-Method in Google Charts that I am missing. I also read a lot about Comet, but I never implemented that concept.
Has anyone else run into that issue?
Implementing AJAX on a timer is the easiest solution:
// using jQuery for simplicity, but you can implement in other libraries or vanilla javascript if you want
function drawChart() {
var options = {
title: 'Company Performance',
vAxis: {title: 'Year', titleTextStyle: {color: 'red'}}
};
var chart = new google.visualization.BarChart(document.getElementById('chart_div'));
function updateChart () {
$.ajax({
url: 'path/to/data/source/',
data: {/* any parameters you need to pass to the server to get your data back */},
dataType: /* text, json, XML, whatever your server returns */,
success: function (response) {
// use response to create/update DataTable
chart.draw(data, options);
// update the chart again in 2 seconds
setTimeout(updateChart, 2000);
},
error: function (response) {
// handle errors
}
});
}
updateChart();
}
Using a Comet service is a bit more complicated to implement, as it requires setting up something like Socket.Io in javascript and on your server.
Using a Comet service will guarantee the freshest data in the chart at all times, while AJAX is simpler to implement. Comet requires sustaining an active connection to your server while AJAX makes multiple independent requests.