After looking for other answers to make a variable global I am struggeling for some time now, it looks quite simple but it just doesn't seem to work.
My code is getting data from a CSV file and returning a variable called 'chart' containing an Array. This Array variable is to be used outside the function in a Highchart graph. (The local returned Array is correct)
I am trying to make the variable inside the function "global" by attaching it as a property of the window. Like this: turn javascript local variable into global variable
But in my code this doesn't work out:
$(document).ready(function() {
$.ajax({
type: "GET",
url: "data/data.csv",
async: false,
dataType: "text",
success: function(data) {processData(data);}
});
});
function processData(data) {
var table = data.split("\n").map(line => line.split(","));
var categories = table[0].slice(2).map(e=>e*1);
data = table.slice(1).map(a => ({"name": a[0], "id": parseInt(a[1]), "data": a.slice(2).slice(0).map(e=>e*1)}));
var lengthdata = data.length - 1;
var chart = data.splice(0, lengthdata);
window.chartglobal = chart;
console.log(chart);
};
console.log(chartglobal);
What am I missing here or are there better ways than the window option for mmy specific situation?
EDIT:
The code is used in leaflet where the data is connected to leaflet markers using map.on and a marker id. That way is doesn't matter that the call ajax request is a pseudo ready event which is fired after trying to get the global value. I don't know what changing the async to 'true' alters but it works either way.
The variable is used in a map.on like this:
map.on('popupopen', function(e) {
var marker = e.popup._source.feature.id;
var search = function(name) {
for(var key in chartglobal) {
if(chartglobal[key].id === name) {
return chartglobal[key];
}}};
var outputhighchart = search(marker);
var chartdef = [];
chartdef.push(outputhighchart);});
The console.log was not logging because of the ajax call, the problem was somewhere in the map.on, which I overlooked because focusing on the global variable. Thanks for helping me out and directing in the right way.