Passing values between two javascript in a html - javascript

I have a case where i need to load a char based on the input from another javascript. But it doesn't work in my case. I have added the code below:
<script type="text/javascript">
// Load the Visualization API and the piechart package.
google.load('visualization', '1', {'packages':['corechart', 'table']});
// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(drawChart);
function drawChart() {
var json = $.ajax({
url: fileURL, // make this url point to the data file
dataType: 'json',
cahce:false,
async: false
}).responseText;
// Create our data table out of JSON data loaded from server.
var data = new google.visualization.DataTable(json);
var options = {
title: graphTitle,
is3D: 'true',
width: 800,
height: 600
};
var tableOptions = {
title: 'App Listing'
};
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
and I pass the value for graphtitle and fileURL as below:
<script type="text/javascript">
$(document).ready(function () {
var fileURL = "";
var graphTitle = "";
function showDiv() {
if($firstCheck) {
var selText;
$("#dd4 li a").show(function () {
selText = $(this).text();
});
if(selText !== "Factor"){
if(selText == "IA Architecture Usage"){
fileURL = "get_json.php";
graphTitle = "IA Architecture Variation";
}else if(selText == "Tablet to Phone"){
fileURL = "get_tablet_support.php";
graphTitle = "Tablet Usage Variation";
}
document.getElementById('chart_div').style.display = "block";
}
}else{
document.getElementById('chart_div').style.display = "none";
}
}
</script>
Both these javascript are within the same file. I can't pass the fileURL and graphTitle when I used the above code. Any idea how to solve this issue?

Use global variables with window. E.g.
$(document).ready(function () {
window.fileURL = "";
window.graphTitle = "";
});
Don't specify "var" or it will only be within the scope of the function.
EDIT: Also make sure that the script in which your variables are assigned initially is before the other one.

How about something a bit more OO oriented (not really OO, but less inline code) ? It's cleaner and easier to read/maintain ..example could still use some work, but i"m sure you get the idea.
function loadChart(title, url) {
// Load the Visualization API and the piechart package.
google.load('visualization', '1', {'packages':['corechart', 'table']});
// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(drawChart);
function drawChart() {
var json = $.ajax({
url : url, // make this url point to the data file
dataType: 'json',
cahce : false,
async : false
});
// Create our data table out of JSON data loaded from server.
var data = new google.visualization.DataTable(json);
var options = {
title : title,
is3D : 'true',
width : 800,
height: 600
};
var tableOptions = {
title: 'App Listing'
};
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
}
$(document).ready(function () {
var fileURL = "";
var graphTitle = "";
function showDiv() {
if($firstCheck) {
var selText;
$("#dd4 li a").show(function () {
selText = $(this).text();
});
if(selText !== "Factor") {
if(selText == "IA Architecture Usage"){
fileURL = "get_json.php";
graphTitle = "IA Architecture Variation";
} else if(selText == "Tablet to Phone"){
fileURL = "get_tablet_support.php";
graphTitle = "Tablet Usage Variation";
}
document.getElementById('chart_div').style.display = "block";
}
} else {
document.getElementById('chart_div').style.display = "none";
}
loadChart(graphTitle, fileURL);
}
}
btw i think you have an error in your code: .responseText seems pretty useless to me, and most likely throws an error in itself. Also i have no idea who is calling showDiv() in the code. From the example, i'd say it never fires.

Related

Pie chart export to CSV / XLSX with amCharts.js

I can't find a way to export my data from a pie chart to CSV or XLSX. I checked this link from amCharts.js but I can manage to adapt it to my need.
Here's my code:
function getDataProviderForEventsByFlow(){
$.ajax({
url: restURI,
success: function(data) {
am4core.useTheme(am4themes_kelly);
chartEventsByFLow = am4core.create("events-by-flow", am4charts.PieChart);
chartEventsByFLow.hiddenState.properties.opacity = 0;
chartEventsByFLow.legend = new am4charts.Legend();
var marker = chartEventsByFLow.legend.markers.template.children.getIndex(0);
marker.cornerRadius(12, 12, 12, 12);
marker.strokeWidth = 2;
marker.strokeOpacity = 1;
marker.stroke = am4core.color("#ccc");
chartEventsByFLow.data = data;
var series = chartEventsByFLow.series.push(new am4charts.PieSeries());
series.dataFields.value = "number";
series.dataFields.category = "category";
series.dataFields.color = "color";
series.labels.template.disabled = true;
series.ticks.template.disabled = true;
series.slices.template.tooltipText = "";
}
});
}
And the export functions :
function exportCSVbyFlow() {
chartEventsByFLow.export.toCSV({}, function(data) {
this.download(data, this.defaults.formats.CSV.mimeType, "exportCSVvolumetryByFlow.csv");
});
}
function exportXLSXbyFlow() {
chartEventsByFLow.export.toXLSX({}, function(data) {
this.download(data, this.defaults.formats.XLSX.mimeType, "exportXLSXvolumetryByFlow.xlsx");
});
}
This is the output in console:
Cannot read property 'toCSV' of undefined
Cannot read property 'toXLSX' of undefined
Thank you !
The code you give is using v4 but the link you're trying to use as an example is using v3.
Have you seen this page? It shows a way to add a menu to a chart with different export options. It also talks about programatically exporting using code like:
chart.exporting.export("csv");

Loop JS object data in multiple arrays

I have some data in a Google Spreadsheet, which I'm pulling with Tabletop.js. I'm able to display my data as well in my showInfo() function. All good.
Now I try to achieve to display this data in a default Google Chart. In this case I use their map package to display my data on a map. They provided me some sample code, see here.
At the moment I'm struggling with the following function, whole code in my Fiddle:
mapdata.addRows([
// PREFERRED DATA TO COLLECT:
// [data.geoloc, data.GM_NAAM, 'blue' ],
// THE HARDCODED WAY:
['Kerkbrink 2 ANLOO', 'ANLOO', 'green'],
['Grote Kerkstraat 32 WIJK EN AALBURG', 'WIJK EN AALBURG', 'blue']
]);
How do I approach? I managed to display all data with a forEach in the showInfo function, but this does not work in this array.
I'm pretty new in JS-land, so I appreciate every help on achieving this.
Thanks in advance!
please find the updated fiddle here
is this what you are looking for ?
updated js code:
/* 1: tabletop shizzle */
var publicSpreadsheetUrl = 'https://docs.google.com/spreadsheets/d/1cpSdKrQK0DfRoC9_xgmAqwVaDqw8BKMOL7drA_QFIn0/edit?usp=sharing';
function init() {
Tabletop.init( { key: publicSpreadsheetUrl,
callback: showInfo,
simpleSheet: true } )
}
function showInfo(data, tabletop) {
alert('Successfully processed!')
var chartdiv = document.querySelector(".chart_div");
console.log("data: ", data);
data.forEach( function(data) {
// card
var card = document.createElement('div');
card.classList.add("card");
//content
var content = document.createElement('div');
content.classList.add('content');
content.innerHTML = data.GM_NAAM + ' ' + data.geoloc;
// append
chartdiv.appendChild(card);
card.appendChild(content);
});
// trigger the google charts drapMap function and send the data to it
drawMap(data);
}
window.addEventListener('DOMContentLoaded', init);
/* 2: google chart shizzle */
google.charts.load('current', {
'packages': ['map'],
// DEFAULT GOOGLE API KEY
'mapsApiKey': 'AIzaSyD-9tSrke72PouQMnMX-a7eZSW0jkFMBWY'
});
google.charts.setOnLoadCallback(drawMap);
function drawMap(data) {
var mapdata = new google.visualization.DataTable();
mapdata.addColumn('string', 'Address');
mapdata.addColumn('string', 'Location');
mapdata.addColumn('string', 'Marker')
console.log(data);
data = data ? data : [];
var rows = [];
data.forEach(function(item){
rows.push([item.GM_NAAM, item.geoloc, 'green'])
})
// THIS IS THE PART I NEED THE DATA.
mapdata.addRows(rows);
// SOME OPTIONS
var url = 'https://icons.iconarchive.com/icons/icons-land/vista-map-markers/48/';
var options = {
zoomLevel: 7,
showTooltip: true,
showInfoWindow: true,
useMapTypeControl: true,
icons: {
blue: {
normal: url + 'Map-Marker-Ball-Azure-icon.png',
selected: url + 'Map-Marker-Ball-Right-Azure-icon.png'
},
green: {
normal: url + 'Map-Marker-Push-Pin-1-Chartreuse-icon.png',
selected: url + 'Map-Marker-Push-Pin-1-Right-Chartreuse-icon.png'
}
}
};
var map = new google.visualization.Map(document.getElementById('map_div'));
map.draw(mapdata, options);
}

Google charts javascript error

I'm trying to display a google pie chart from data recovered from excel sheet.
The returned String is described below which I'm passing in google.visualization.arrayToDataTable();
The code that I have used is:
<script type="text/javascript">
google.charts.load("current", {packages:["corechart"]});
google.charts.setOnLoadCallback(drawChart);
var str = '<%= JSNstring %>'; //returned string from C#.
var res= str.replace(/""/g,"'");
res=res.replace(/"/g,"'");
//
var ss=[res];
document.write(ss); //the output of this is:
[['Solution','TOTAL'],['Check',23],['FULL',18],['POP',109]]
function drawChart() {
var data = google.visualization.arrayToDataTable(ss);
var options = {
title: 'My Daily Activities',
pieHole: 0.4,
};
var chart = new google.visualization.PieChart(document.getElementById('donutchart'));
chart.draw(data, options);
}
</script>
This is showing error :
JavaScript runtime error: First row is not an array.
Please tell me what I'm doing wrong and how to correct it.
Thanks in advance.
`document.write(ss);`
Is only for this example, right? If it not so remove it and try to see inside your function what is the value of ss, like this-
function drawChart() {
console.write(ss);
var data = google.visualization.arrayToDataTable(ss);
var options = {
title: 'My Daily Activities',
pieHole: 0.4,
};
var chart = new google.visualization.PieChart(document.getElementById('donutchart'));
chart.draw(data, options);
}
Update
Try to rewrite your function drawChart() like this-
function drawChart() {
var str = '<%= JSNstring %>'; //returned string from C#.
var res= str.replace(/""/g,"'");
res=res.replace(/"/g,"'");
//
var ss=[res];
var data = google.visualization.arrayToDataTable(ss);
var options = {
title: 'My Daily Activities',
pieHole: 0.4,
};
var chart = new google.visualization.PieChart(document.getElementById('donutchart'));
chart.draw(data, options);
}
Update 2
I created for you jsfiddle here jsfiddle, with your array in hard code, as you can see it is working here.So your problem is something with the server side or with the value of ss.
I think you need to parse the string into an array, try this...
google.charts.load("current", {packages:["corechart"]});
google.charts.setOnLoadCallback(drawChart);
var str = '<%= JSNstring %>'; //returned string from C#.
var res= str.replace(/""/g,"'");
res=res.replace(/"/g,"'");
var ss='[' + res + ']';
function drawChart() {
var data = google.visualization.arrayToDataTable(eval(ss));
var options = {
title: 'My Daily Activities',
pieHole: 0.4,
};
var chart = new google.visualization.PieChart(document.getElementById('donutchart'));
chart.draw(data, options);
}

dom is undefined error when trying to upload shapefile

I have been working on an arcgis project for the last two weeks and I have ran into an issue with my upload shapefile function in my code. I keep getting an dom is undefined error and I don't know what to do.
Here is the code:
<div class="modal fade" id="UpdateShapefileForm" tabindex="-1" role="dialog" aria- labelledby="Set View" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<form enctype="multipart/form-data" method="post" id="uploadForm">
<div class="field">
<label class="file-upload">
<span><strong>Add File</strong></span>
<input type="file" name="file" id="inFile"/>
</label>
</div>
</form>
</div>
</div>
</div>
</div>
<script src="http://js.arcgis.com/3.9/"></script>
<script src="/static/js/mapping/mapobject.js" type="text/javascript"></script>
<script src="/static/js/mapping/mapmanager.js" type="text/javascript"></script>
<script type="text/javascript">
var map, toolbar;
var PROJECT_OUTLINE, PROJECT_FILL, PARCEL_OUTLINE, PARCEL_FILL, PLOT_OUTLINE, PLOT_FILL;
var toolbarEvent;
var mapManager = new MapManager();
var markerPictures = {
'project': '/static/assets/grnball.png',
'parcel': '/static/assets/bluball.png',
'plot': '/static/assets/redball.png'
}
require([
"esri/config",
"esri/InfoTemplate",
"esri/map",
"esri/request",
"esri/geometry/scaleUtils",
"esri/layers/FeatureLayer",
"esri/renderers/SimpleRenderer",
"esri/symbols/PictureMarkerSymbol",
"esri/symbols/SimpleFillSymbol",
"esri/symbols/SimpleLineSymbol",
"esri/symbols/SimpleMarkerSymbol",
"dojo/dom",
"dojo/json",
"dojo/on",
"dojo/parser",
"dojo/sniff",
"dojo/_base/array",
"esri/Color",
"dojo/_base/lang",
"dijit/layout/BorderContainer",
"dijit/layout/ContentPane",
"dojo/domReady!"
], function(
esriConfig, InfoTemplate, Map, request, scaleUtils, FeatureLayer,
SimpleRenderer, PictureMarkerSymbol, SimpleFillSymbol, SimpleLineSymbol, SimpleMarkerSymbol,
dom, JSON, on, parser, sniff, arrayUtils, Color, lang
) {
map = new Map("mapcanvas", {
center: [-56.049, 38.485],
zoom: 3,
basemap: "hybrid"
});
map.on("load", function() {
$("#waiting_img").hide();
createToolbar();
setConstants();
parser.parse();
var portalUrl = "http://www.arcgis.com";
esriConfig.defaults.io.proxyUrl = "/proxy";
on(dom.byId("uploadForm"), "change", function (event) {
var fileName = event.target.value.toLowerCase();
if (sniff("ie")) { //filename is full path in IE so extract the file name
var arr = fileName.split("\\");
fileName = arr[arr.length - 1];
}
if (fileName.indexOf(".zip") !== -1) {//is file a zip - if not notify user
generateFeatureCollection(fileName);
}
else {
dom.byId('upload-status').innerHTML = '<p style="color:red">Add shapefile as .zip file</p>';
}
map.graphics.on("click", function(evt) {
console.log("geometry type: " + evt.graphic.geometry.type);
if(evt.graphic.geometry.type == "polygon")
{
selectPolygon();
}
else if(evt.graphic.geometry.type == "multipoint" || evt.graphic.geometry.type == "point")
{
selectMarker();
}
});
});
});
});
function generateFeatureCollection (fileName) {
var name = fileName.split(".");
//Chrome and IE add c:\fakepath to the value - we need to remove it
//See this link for more info: http://davidwalsh.name/fakepath
name = name[0].replace("c:\\fakepath\\", "");
dom.byId('upload-status').innerHTML = '<b>Loading </b>' + name;
//Define the input params for generate see the rest doc for details
//http://www.arcgis.com/apidocs/rest/index.html?generate.html
var params = {
'name': name,
'targetSR': map.spatialReference,
'maxRecordCount': 1000,
'enforceInputFileSizeLimit': true,
'enforceOutputJsonSizeLimit': true
};
//generalize features for display Here we generalize at 1:40,000 which is approx 10 meters
//This should work well when using web mercator.
var extent = scaleUtils.getExtentForScale(map, 40000);
var resolution = extent.getWidth() / map.width;
params.generalize = true;
params.maxAllowableOffset = resolution;
params.reducePrecision = true;
params.numberOfDigitsAfterDecimal = 0;
var myContent = {
'filetype': 'shapefile',
'publishParameters': JSON.stringify(params),
'f': 'json',
'callback.html': 'textarea'
};
//use the rest generate operation to generate a feature collection from the zipped shapefile
request({
url: portalUrl + '/sharing/rest/content/features/generate',
content: myContent,
form: dom.byId('uploadForm'),
handleAs: 'json',
load: lang.hitch(this, function (response) {
if (response.error) {
errorHandler(response.error);
return;
}
var layerName = response.featureCollection.layers[0].layerDefinition.name;
dom.byId('upload-status').innerHTML = '<b>Loaded: </b>' + layerName;
addShapefileToMap(response.featureCollection);
}),
error: lang.hitch(this, errorHandler)
});
}
function errorHandler (error) {
dom.byId('upload-status').innerHTML =
"<p style='color:red'>" + error.message + "</p>";
}
function addShapefileToMap (featureCollection) {
//add the shapefile to the map and zoom to the feature collection extent
//If you want to persist the feature collection when you reload browser you could store the collection in
//local storage by serializing the layer using featureLayer.toJson() see the 'Feature Collection in Local Storage' sample
//for an example of how to work with local storage.
var fullExtent;
var layers = [];
arrayUtils.forEach(featureCollection.layers, function (layer) {
var infoTemplate = new InfoTemplate("Details", "${*}");
var featureLayer = new FeatureLayer(layer, {
infoTemplate: infoTemplate
});
//associate the feature with the popup on click to enable highlight and zoom to
featureLayer.on('click', function (event) {
map.infoWindow.setFeatures([event.graphic]);
});
//change default symbol if desired. Comment this out and the layer will draw with the default symbology
fullExtent = fullExtent ?
fullExtent.union(featureLayer.fullExtent) : featureLayer.fullExtent;
layers.push(featureLayer);
});
map.addLayers(layers);
map.setExtent(fullExtent.expand(1.25), true);
dom.byId('upload-status').innerHTML = "";
}
function setConstants() {
PROJECT_OUTLINE = new esri.Color(([0,255,0]));
PROJECT_FILL = new esri.Color([0,255,0,0.5]);
PARCEL_OUTLINE = new esri.Color(([0,0,255]));
PARCEL_FILL = new esri.Color([0,0,255,0.5]);
PLOT_OUTLINE = new esri.Color(([255,0,0]));
PLOT_FILL = new esri.Color([255,0,0,0.5]);
}
function createToolbar() {
toolbar = new esri.toolbars.Draw(map);
}
function drawEnd(geometry, pType, outline, fill) {
toolbar.deactivate();
map.showZoomSlider();
console.log("geometry: " + geometry.type);
var text_symbol = null;
switch (geometry.type) {
case "point":
case "multipoint":
symbol = new esri.symbol.PictureMarkerSymbol(markerPictures[pType], 13, 13);
break;
default:
symbol = new esri.symbol.SimpleFillSymbol();
symbol.setColor(fill);
symbol.setOutline(new esri.symbol.SimpleLineSymbol(esri.symbol.SimpleLineSymbol.STYLE_SOLID, outline, 2));
break;
}
var graphic = new esri.Graphic(geometry, symbol);
map.graphics.add(graphic);
var map_obj = new MapObject(pType, pType, graphic, geometry.type);
mapManager.Add(map_obj);
if(toolbarEvent != null)
{
toolbarEvent.remove();
toolbarEvent = null;
}
}
error happens specifically on this line:
dom.byId('upload-status').innerHTML = '<b>Loading </b>' + name;
You've got a simple scoping error - the variable dom is declared as an argument to this function:
require([...,"dojo/dom",...], function(...,dom,...) {...});
Your next function declaration is this:
function generateFeatureCollection (fileName) {
...
dom.byId(...);
...
}
but the variable dom is not defined in this function, so you can't use it here. You need to either pass it to the function:
function generateFeatureCollection (fileName, dom) {...}
which gets very clumsy if you're going to pass it around to every function, assign the dom variable in your require function to a global variable, or redeclare it where you need it. From the docs:
require(["dojo/dom"], function(dom){
// fetch a node by id="someNode"
var node = dom.byId("someNode");
});

Google Visualization Charts ajax data

I'm trying to dynamically render a google visualization chart with an AJAX call in flask to set the data. User enters input then clicks a link which calls the ajax function to get the data. the "/ajax_test" view will return a json object but the problem I have is i don't know how to correctly pass the data back into the DataTable function. How do i pass the json data i'm getting from ajax to a variable for the drawchart function?
Chart function:
<script type="text/javascript">
function drawChart(){
var data = new google.visualization.DataTable(jsondata);
var options = {
explorer: {},
}; //end options
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
Ajax function:
<script type=text/javascript>
$(function() {
$('a#DrawChart').bind('click', function() {
$.getJSON($SCRIPT_ROOT + '/ajax_test',
{//input data sent to view}
, function(data) {
var jsondata = data.test_json;
drawChart();
});
return false;
});
});
</script>
This method doesn't know where jsondata comes from:
function drawChart() {
var data = new google.visualization.DataTable(jsondata);
...
}
Add jsondata as a parameter:
function drawChart(jsondata) {
var data = new google.visualization.DataTable(jsondata);
...
}
And then in your Ajax call pass jsondata to the method:
function(data) {
var jsondata = data.test_json;
drawChart(jsondata);
}
I have done something similar using the following code, this is a jinja2 example, so you have do adapt your code (change the way jsonData var is initialized):
<script type="text/javascript">
//load the Google Visualization API and the chart
google.load('visualization', '1', {'packages': ['corechart']});
google.setOnLoadCallback (createChart);
var jsonData = {{ value_columns | tojson | safe }}
function createChart() {
var dataTable = new google.visualization.DataTable(jsonData);
var chart = new google.visualization.LineChart(document.getElementById('chart'));
//define options for visualization
var options = {is3D: 'no', title: 'Some Title' };
attachRedrawForTab(chart, dataTable, options);
attachRedrawForAccord(chart, dataTable, options);
//draw our chart
chart.draw(dataTable, options);
}
</script>

Categories

Resources