javascript.netinternet-explorer-11sharepoint-2013

How to Retrieve User Properties with JavaScript


I have the following code in a Content Editor Web Part, which retrieves the current user's name and displays it in a message box :

<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> 
<script language="javascript" type="text/javascript"> 

function getUser() {
    var userid = _spPageContextInfo.userId;
    //alert(userid);

    var requestUri = _spPageContextInfo.webAbsoluteUrl + "/_api/web/getuserbyid(" + userid + ")";
    var requestHeaders = { "accept": "application/json;odata=verbose" };
    $.ajax({
        url: requestUri,
        contentType: "application/json;odata=verbose",
        headers: requestHeaders,
        success: onSuccess,
        error: onError
    }); 
    
    function onSuccess(data, request) {
        var loginName = data.d.Title;
        alert(loginName);
    } 
    function onError(error) {
        alert("Error on retrieving current user.");
    }
}


    $(document).ready(function() {
        getUser();
    });
</script>

I was also able to display the email with alert(data.d.Email);.

However, when I try calling data.d.Groups (as per the documentation - which shows that a Groups property exists), I see a message box with [object Object].

How can I retrieve the individual items from this (what I am assuming is a) collection?

I have tried :

var group = data.d.Groups[0];
alert(group);

But this just comes up with undefined.

Am I wrong in thinking that this object will contain my Department?

Either way, is there a way of iterating through these objects, or have I done it correctly but on an empty array?


Attempt at Logging the groups

function onSuccess(data, request) {
    var loginName = data.d.Title;
    console.log(loginName);
    
    var groups = data.d.Groups;
    console.log(groups);
} 

I can't see either of the above logs in the F12 console window... (Internet Explorer)


Attempt 2 - Logging Successful

Using the code below, I was able to achieve the same results as before, but this time the console.log() calls actually worked (still have no idea why the previous ones didn't):

ExecuteOrDelayUntilScriptLoaded(init,'sp.js');
var currentUser;
function init(){
    this.clientContext = new SP.ClientContext.get_current();
    this.oWeb = clientContext.get_web();
    currentUser = this.oWeb.get_currentUser();
    this.clientContext.load(currentUser);
    this.clientContext.executeQueryAsync(Function.createDelegate(this,this.onQuerySucceeded), Function.createDelegate(this,this.onQueryFailed));
}

function onQuerySucceeded() {
    
    var groups = currentUser.get_groups();
    alert(groups);
    console.log(groups);

    var name = currentUser.get_loginName(); 
    alert(name);
    console.log(name);
    
    var id = currentUser.get_id();
    alert(name);
    
    var title = currentUser.get_title();
    alert(title);
    
    var email = currentUser.get_email();
    alert(email);
}

function onQueryFailed(sender, args) {
    alert('Request failed. \nError: ' + args.get_message() + '\nStackTrace: ' + args.get_stackTrace());
}

After calling console.log(groups);, the following appeared in the F12 console :

enter image description here


Solution

  • I was able to find a rather ugly solution to this, but it does work.

    First, we need to call some .js files in preperation:

    <script src="//ajax.aspnetcdn.com/ajax/jQuery/jquery-1.9.0.min.js"></script>
    <script src="/_layouts/15/SP.Runtime.js"></script>
    <script src="/_layouts/15/SP.js"></script>
    <script src="/_layouts/15/SP.UserProfiles.js"></script>
    

    Then, inside a <script language="javascript" type="text/javascript"> tag, we declare some global variables and 2 main functions...

    var currentUser;
    var currentUserName;
    var property = "Department";    
    

    1. GetCurrentUserProperty(property):

    This function actually only gets the current user for us and, if successful will call loadUserData (which actually gets the property we defined earlier for the given user:

    // This function first gets the current user's firstname.lastname username (e.g. Joe.Bloggs).
    // If this is successful, it calls the loadUserData function, which will retrieve the user's
    // property which was defined in the global "property" variable.
    function GetCurrentUserProperty(){
        this.clientContext = new SP.ClientContext.get_current();
        this.oWeb = clientContext.get_web();
        currentUser = this.oWeb.get_currentUser();
        this.clientContext.load(currentUser);
        this.clientContext.executeQueryAsync(onQueryUserSuccess, onQueryUserFail);
    }
    function onQueryUserSuccess() {
        // If the query is successful, extract the first.last username and then call loadUserData
        window.currentUserName= currentUser.get_loginName().split("\\")[1]; 
        loadUserData(window.currentUserName);
    }
    function onQueryUserFail(sender, args) {
        alert('Failed to retrieve user name');
    }
    

    2. loadUserData

    This function takes the given user.name and will get the property that is stored in property for that user. Here, in the success function, I am just outputting the result to an alert window:

    function loadUserData(userName){        
        //Get Current Context   
        var clientContext = new SP.ClientContext.get_current();
    
        //Get Instance of People Manager Class
        var peopleManager = new SP.UserProfiles.PeopleManager(clientContext);
    
        //Property to fetch from the User Profile
        var strDepartment = window.property;
    
        //If you are on On-Premise:
        var targetUser = "BARDOM1\\" + userName;
    
        //Create new instance of UserProfileProperty
        departmentProperty = peopleManager.getUserProfilePropertyFor(targetUser, strDepartment)
    
        //Execute the Query. (No load method necessary)
        clientContext.executeQueryAsync(onSuccess, onFail);
    }
    function onSuccess() {    
        var messageText = window.property + " is " + departmentProperty .get_value();
        alert(messageText);
    }
    function onFail(sender, args) {
        alert("Error: " + args.get_message());
    }
    

    Finally, to actually run this process, we need to call GetCurrentUserProperty();. I put all of this code into a file called testproperty.js and saved it in SiteAssets. Then, on the page where we want the code to run, add a Content Editor Web Part and in edit -> path the call is ../../SiteAssets/testproperty.js. This will run once the page load - hope this helps anyone else who may be stuck on this!