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("Sub Navigation");

         function getData(){
              headers: headers,
              success: function success(data) {
              var results;
                if(lName == "Navigation"){
                }else {
                    subList = data.d.results;
                    console.log(subList); //<-------CONTAINS data


                            function buildSubNavBar(subNavID){
                    //More code missing

                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;

              return ddDiv;
  • 1
    Where is your getData() and what it does? Also if you are trying to access the global variable subList in buildSubNavBar() function then remove var before var subList = getData("Sub Navigation"); as it is not aceesing the variable from global scope, instead it is creating a new variable with same name. Dec 5 '19 at 16:43
  • sorry..I modified my question. getInfo() is getData(). I made the correction
    – OLA
    Dec 5 '19 at 17:37
  • 1
    You need to make your REST call as a sync call. Try adding async:false to your REST call and just call the function like getData("Sub Navigation") instead of var subList = getData("Sub Navigation"); OR you can use promises in your function call. Check this to understand using promises with Ajax call. Dec 5 '19 at 17:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.