Pie chart export to CSV / XLSX with amCharts.js - javascript

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");

Related

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);
}

how to implement ng-handsontable lazy loading for angularjs

I am working on an angularJS project where i have met with a requirement to implement ng-handsontable lazy loading feature. The data is huge such that if allowed to display all at once will make the site very slow.
Is there any way to implement the lazy loading feature for ng-handsontable for angularJS.
I have tried using the pure javascript to implement it, but not working for angularjs.
Html code is:
<div id="example1" class="hot handsontable htRowHeaders htColumnHeaders">
</div>
Javascript code is:
document.addEventListener("DOMContentLoaded", function() {
// mock service for getting data
var fetchData = function(n) {
return Handsontable.helper.createSpreadsheetData(n, 3);
};
// variables
var example = document.getElementById('example1');
var hot;
var data = fetchData(100);
var compute_window = function(e) {
var rowCount = hot.countRows();
var rowOffset = hot.rowOffset();
var visibleRows = hot.countVisibleRows();
var lastRow = rowOffset + (visibleRows * 1);
var lastVisibleRow = rowOffset + visibleRows + (visibleRows/2);
var threshold = 15;
if(lastVisibleRow > (rowCount - threshold)) {
loadMoreData(rowCount);
}
};
// initialize HOT
hot = new Handsontable(example,{
data: data,
rowHeaders: true,
colHeaders: true,
afterScrollVertically: compute_window
});
// load data and render
var loadMoreData = function(n) {
// call data service
var incoming = fetchData(n);
incoming.forEach(function(d) {
data.push(d);
});
hot.render();
};
});
Anybody please help.
Thanks

Condition for logged==true

I want show some option of picker just when user log in.
So I tried====>
I added a global variable in alloy.js>>
var aux=0;
And in my index.js i did>>
loginReq.onload = function()
{
var json = this.responseText;
var response = JSON.parse(json);
if (response.logged == true)
{
aux=1;
homes.open();
$.index.close();
alert("Welcome " + response.name + ". Your email is: " + response.email);
}
else
{
alert(response.message);
}
};
Last part in other controller home.js>>
Alloy.Globals.loading.hide();
var picker = Ti.UI.createPicker({
left:10,
top: 10,
height:50,
opacity:0.5, backgroundColor: "Black", borderRadius:"2"
});
var data = [];
data.push(Titanium.UI.createPickerRow({id:'0',title:'Mis cursos'}));
data.push(Titanium.UI.createPickerRow({id:'1',title:'Todos Cursos'}));
if(aux===1){
data.push(Titanium.UI.createPickerRow({id:'2',title:'Crear'}));
}
picker.add(data);
the problem is I tried to use if(aux===1) or if(aux==1), but didnt work both... Always no show "Crear" in picker. Why? Need your helps! and Thanks!
The issue is that you are not defining your global variable in alloy.js properly.
As you defined var aux=0; in alloy.js , so this variable is only available in alloy.js. To make it usable in other files define it as following :
In alloy.js :
Alloy.Globals.aux = 0;
To fetch it in index.js and home.js use :
var auxValue = Alloy.Globals.aux;
So your home.js would look like :
Alloy.Globals.loading.hide();
var picker = Ti.UI.createPicker({
left:10,
top: 10,
height:50,
opacity:0.5, backgroundColor: "Black", borderRadius:"2"
});
var data = [];
data.push(Titanium.UI.createPickerRow({id:'0',title:'Mis cursos'}));
data.push(Titanium.UI.createPickerRow({id:'1',title:'Todos Cursos'}));
if(Alloy.Globals.aux === 1){ //changed here
data.push(Titanium.UI.createPickerRow({id:'2',title:'Crear'}));
}
picker.add(data);
Note : also check the proper way to manage objects in alloy.js

Passing values between two javascript in a html

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.

Grid can not be used in this ('quirks') mode Error

I want to make grid with jquery.I read data from xml. when I run it on Chrome browser it works.But when I try it on IE it gives this error.
Grid can not be used in this ('quirks') mode!
I write this code:
var datasource_url = "/Data/XML_Data.xml";
function makeID(string) {
return string.toLowerCase().replace(/\s/g, "_")
}
$(function() {
$.loadGrid = function() {
$.ajax({
cache: false,
url :datasource_url ,
dataType: "xml",
success: function(data, res) {
var colNames = new Array;
var colIDs = new Array;
var colModel = new Array;
var datas = new Array;
var metadata = $(data).find("metadata").each(function() {
$(this).find('item').each(function() {
var colname = $(this).attr('name');
var colid = makeID($(this).attr('name'));
var coltype = $(this).attr('type');
var collength = $(this).attr('length');
var sorttype = null;
var sortable = false;
switch(coltype) {
case "xs:double":
sorttype = "float";
sortable = true;
break;
case "xs:string":
default:
sorttype = "text";
sortable = true;
break;
}
colNames[colNames.length] = colname;
colIDs[colIDs.length] = colid;
colModel[colModel.length] = {name: colid, index: colid, width: 200, align: "center", sorttype: sorttype, sortable: sortable}
});
});
var options = {
datatype: "local",
height: 500,
colNames: colNames,
colModel: colModel,
multiselect: false,
caption : "Data Grid",
rowNum : 1000,
rownumbers: true
}
$("#datagrid").jqGrid(options);
$(data).find("data").each(function() {
var i=0;
$(this).find('row').each(function() {
var idx = 0;
var rowdata = new Object;
$(this).find('value').each(function() {
var ccolid = colIDs[idx];
if (ccolid) {
rowdata[ccolid] = $(this).text();
}
idx++;
})
$("#datagrid").jqGrid('addRowData', i+1, rowdata)
i++
})
})
}
})
}
$.loadGrid();
/*
$("#btnLoadGrid").click(function() {
//$(this).attr("disabled", "disabled")
$.loadGrid();
})
*/
});
</script>
How can I fix this.
I recommend you to include
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
at the beginning of <head> of your XHTML document. It will switch off the "Compatibility View" for the page. Some time ago I included the line in all code examples which I found on the official jqGrid wiki (see here) because the problem which you describe is common.
As mentioned in the comments, you'll need a correct doctype to force IE out of quirks mode. It looks like you are using an XHTML doctype, which is not compatible with some aspects of HTML5. Try using the HTML5 doctype on the first line of your HTML page: <!DOCTYPE html>
Here's a good article on the different doctypes and their relationship to HTML5.

Categories

Resources