I am having a scope issue and not sure why. I am dynamically creating a navigation with drop-down. It does get created but the drop-down is not rendering even though the caret is showing. I believe it's a scope issue. I am using REST API to get data from my list but I'm unable to populate the global variable. Any help would be much appreciated.
var subList=[]; //global scope
$(document).ready(function() {
var main_nav_bar;
var sub_nav_bar;
getData("Navigation");
getData("Sub Navigation");
});
function getData(){
$.ajax({
url:endPointUrl,
type:"GET",
headers: headers,
success: function success(data) {
var results;
if(lName == "Navigation"){
buildNavBar(data.d.results);
}else {
subList = data.d.results;
console.log(subList); //<-------CONTAINS data
}
}
});
}
function buildSubNavBar(subNavID){
//More code missing
console.log("Sublist");
console.log(subList); //<-------CONTAINS no data
for (var i=0; i<subList.length; i++){
console.log(subList[i].id + "===" + subNavID);
if (subList[i].id === subNavID){
var li = _createEl("li");
var a = _createEl("a");
var aTextNode = document.createTextNode(subList[i].URLNAME);
a.href = subList[i].URL;
a.appendChild(aTextNode);
ddContent.appendChild(a)
}
}
ddDiv.appendChild(ddContent)
return ddDiv;
}
getData()
and what it does? Also if you are trying to access the global variablesubList
inbuildSubNavBar()
function then removevar
beforevar subList = getData("Sub Navigation");
as it is not aceesing the variable from global scope, instead it is creating a new variable with same name. – Ganesh Sanap Dec 5 '19 at 16:43getInfo()
isgetData()
. I made the correction – OLA Dec 5 '19 at 17:37async:false
to your REST call and just call the function likegetData("Sub Navigation")
instead ofvar subList = getData("Sub Navigation");
OR you can use promises in your function call. Check this to understand using promises with Ajax call. – Ganesh Sanap Dec 5 '19 at 17:43