I seem to be having trouble returning a JSON object as all I get is an undefined variable.
The code below is supposed to fetch a JSON element from an API. It appears to work within the success: function, but when attempting to use that data elsewhere, it just shows 'undefined.'
var datas;
datas = fetchData();
//fetchData();
generateChart(datas)
alert('2datass' + datas); // this results in undefined
function generateChart(data){
alert(data); //outputs as undefined
}
function fetchData(){
alert('ajax');
$.ajax({
type: "GET",
dataType: "json",
url: "API URL",
success: function(data){
alert(data); // WORKS! and outputs my JSON data
return jQuery.parseJSON(data);
return data;
}
});
};
Any assistance would be greatly appreciated.
SOLUTION
Appreciation for everyone's help.
This seems to resolve the issue
var datas;
datas = obtainData();
alert('2datass' + datas);
console.log(datas);
createChart(datas);
function createChart(data){
alert('createChart' + data);
var dynamicData;
for(var i = 0; i <= data.length-1; i++){
var item = data[i];
dynamicData = dynamicData + {
type: 'column',
name: item.name,
data: [item.difference]
};
}
alert('dynamic' + dynamicData);
var series = [dynamicData,{
type: 'column',
name: 'Jane',
data: [300, 30]
}, {
type: 'column',
name: 'John',
data: [-200, 50]
}];
var options = {
chart: {
renderTo: 'container'
},
title: {
text: 'Account Managers Leaderboard'
},
xAxis: {
categories: ['Month on Month', 'Day on Day']
}
// similar configurations...
};
$(document).ready(function() {
var chart;
chart = new Highcharts.Chart(options);
});
}
function getData(){
//alert('ajax');
var receivedData;
$.ajax({
type: "GET",
dataType: "json",
url: "API URL",
async: false,
success: function(data){
alert('data' + data);
receivedData = data;
}
});
return receivedData;
};