I have a javaScript function that use library Buckets and it should return the value to html. I used console.log to see data inside the function and it's not null. But on the html, it said "undefined".
This is my js code :
function transformToStruct(xmlData)
{
var data = xmlData.item;
var myReturn;
$.getScript("buckets-minified.js", function()
{
var treeData = new buckets.MultiDictionary();
$.each(data, function(i,val)
{
if(typeof data == 'object')
{
$.each(val, function(j, childVal)
{
var dict = new buckets.Dictionary();
dict.set(val["NodeId"]["#text"], val["NodeText"]["#text"]);
treeData.set(val["ParentId"]["#text"], dict);
});
}
});
console.log(treeData)
return treeData;
});
}
This is on the html page that I call transformToStruct function :
var myGTP = new buckets.MultiDictionary();
$.ajax({
url: "http://frparlself6.dhcp.par.xxxx.corp:8000/com/sap/st/ltst/LTST_Backend/frontAccess/example.xsjs?structureId=" + structureId,
dataType : 'jsonp',
type:'GET'
}).always(function() {
var sXml = _JSONFromHANA.body
var xmlData = $.parseXML(sXml);
var xml = xmlToJson(xmlData);
var items = xml["soap-env:Envelope"]["soap-env:Body"]["n0:_-qte_-rfcReadStrucNodesResponse"]["EtNodes"];
myGTP = transformToStruct(items);
console.log(myGTP);
});
Any ideas?
treeData
is the return value of an anonymous function that you pass as an argument to the function getScript
. Your function transformToStruct
doesn't actually have an own return value, so it's not surprising that it is undefined
. Since getScript
works asynchronously you could use a callback instead of a return value:
function transformToStruct(xmlData, callback)
{
var data = xmlData.item;
var myReturn;
$.getScript("buckets-minified.js", function()
{
var treeData = new buckets.MultiDictionary();
$.each(data, function(i,val)
{
if(typeof data == 'object')
{
$.each(val, function(j, childVal)
{
var dict = new buckets.Dictionary();
dict.set(val["NodeId"]["#text"], val["NodeText"]["#text"]);
treeData.set(val["ParentId"]["#text"], dict);
});
}
});
console.log(treeData)
callback(treeData);
});
}
Your function call would then look like this:
var myGTP = new buckets.MultiDictionary();
$.ajax({
url: "http://frparlself6.dhcp.par.xxxx.corp:8000/com/sap/st/ltst/LTST_Backend/frontAccess/example.xsjs?structureId=" + structureId,
dataType : 'jsonp',
type:'GET'
}).always(function() {
var sXml = _JSONFromHANA.body
var xmlData = $.parseXML(sXml);
var xml = xmlToJson(xmlData);
var items = xml["soap-env:Envelope"]["soap-env:Body"]["n0:_-qte_-rfcReadStrucNodesResponse"]["EtNodes"];
transformToStruct(items, function(result) {
myGTP = result;
console.log(myGTP);
});
});
But as mentioned in the comments, you should probably read something about asynchronous functions first.