4 Replies Latest reply on May 30, 2017 2:37 PM by Jeff Shurtliff

    Cannot access variable returned from Ajax API query

    Jeff Shurtliff

      Hi all,

       

      I am trying to use JavaScript/Ajax to check whether or not a user is an employee by checking for a specific Security Group and then setting a global variable which can then be used elsewhere.  I am using the code below in our site header.

       

      var $j = jQuery.noConflict();
          $j.ajax({
              type: 'GET',
              url: '/api/core/v3/people/@me/securityGroups',
              dataType: 'text',
              cache: false,
              success: function (data) {
                  var cleanedJSON = JSON.parse(data.replace("throw 'allowIllegalResourceCall is false.';", ""));
                  jiveGroups = []; // Global array
                  $j(cleanedJSON.list).each(function () {
                      jiveGroups.push(this.name);
                  });
       
        var userType = 'Unknown';
        var groupName = 'Employees';
       
        function checkGroups ( id ) {
        for(i=0; i < jiveGroups.length; i++) {
        if ( jiveGroups[i] == groupName ) {
        return true;
        }
        }
        return false;
        }
      
      
        var checkUser = checkGroups(groupName);
      
      
        if (checkUser === true) {
        userType = 'Employee';
        console.log('userType: ' + userType);
        console.log('User is an employee')
        } else {
        userType = 'Non-Employee';
        console.log('userType: ' + userType);
        console.log('User is not an employee')
        }
              },
              error: function (data) {
                  console.log('Error getting jiveGroups!');
              }
          });
      
      

       

      However when I try to reference the userType variable anywhere else, it always comes back as "undefined" as shown in the screenshots below from the Google Chrome Console.

       

       

      Are there any JavaScript gurus out there that can tell me what I'm doing wrong?

       

      Thanks in advance!