7

I need to get current login User profile properties provide information about SharePoint users, such as display name, email, PictureUrl and other business and personal information including custom properties.Can someone help me achieve this?

Thanks

1

4 Answers 4

9

Yes, please try below code

$(document).ready(function () {

    var currentUser;
    // Ensure that the SP.js is loaded
    if (SP.ClientContext != null) {
        SP.SOD.executeOrDelayUntilScriptLoaded(getCurrentUser, 'SP.js');
    }
    else {
        SP.SOD.executeFunc('sp.js', getCurrentUser);
    }

    function getCurrentUser() {
        var context = new SP.ClientContext.get_current();
        var web = context.get_web();
        currentUser = web.get_currentUser();
        context.load(currentUser);
        context.executeQueryAsync(onSuccessMethod, onRequestFail);
    }

    function onSuccessMethod(sender, args) {
        var account = currentUser.get_loginName();
        var currentUserAccount = account.substring(account.indexOf("|") + 1);
        alert(currentUserAccount);
    }
    // This function runs if the executeQueryAsync call fails.
    function onRequestFail(sender, args) {
        alert('request failed' + args.get_message() + '\n' + args.get_stackTrace());
    }

});
5

You can use this for all properties of the current user

http://siteurl/_api/SP.UserProfiles.PeopleManager/GetMyProperties

Use the following to get the profile information for a specific user

http://siteurl/_api/SP.UserProfiles.PeopleManager/GetPropertiesFor(accountName=@v)?@v='domain\username'

You can also add a Script Editor WebPart on the page to views users information:

<script type='text/javascript'>  


    var workEmail = "";  
    var EmployeeID = "";  
    var Division = "";  
    var userDisplayName = "";  
    var AccountName = "";  

    $.ajax({  

        url: _spPageContextInfo.webAbsoluteUrl + "/_api/SP.UserProfiles.PeopleManager/GetMyProperties",  
        headers: { Accept: "application/json;odata=verbose" },  
        success: function (data) {  
            try {  
                //Get properties from user profile Json response  
                userDisplayName = data.d.DisplayName;  
                AccountName = data.d.AccountName;  
                var properties = data.d.UserProfileProperties.results;  
                for (var i = 0; i < properties.length; i++) {  

                    if (property.Key == "WorkEmail") {  
                        workEmail = property.Value;  
                    }  

                    if (property.Key == "EmployeeID") {  
                        EmployeeID = property.Value;  
                    }  
                    if (property.Key == "Division") {  
                        Division = property.Value;  
                    }  

                }  
                $('#AccountName').text(AccountName);  
                $('#userDisplayName').text(userDisplayName);  
                $('#EmployeeID').text(EmployeeID);  
                $('#workEmail').text(workEmail);  
                $('#Division').text(Division);  


            } catch (err2) {  
                //alert(JSON.stringify(err2));  
            }  
        },  
        error: function (jQxhr, errorCode, errorThrown) {  
            alert(errorThrown);  
        }  
    });  

</script>  

<h2><strong>Employee Details</strong></h2>  
<br />  
AccountName   <span id="AccountName"></span>  
DisplayName   <span id="userDisplayName"></span>  
EmployeeID    <span id="EmployeeID"></span>  
Email Address <span id="workEmail"></span>  
Division      <span id="Division"></span>
1
  • The only weird thing for me - I populated the "Office" field with a value, then I went back and changed it. This code pulled back the old value for the field, while the ECMAScript in the accepted answer pulled back the current value. Any ideas why and how to get it to pull back the current value?
    – vapcguy
    Mar 11, 2019 at 23:00
5

Finally! I solved it using this code that I developed and it works great:

<script type="text/ECMAScript">
    SP.SOD.executeOrDelayUntilScriptLoaded(getUserProperties, 'SP.UserProfiles.js');

    var userProfileProperties;

    function getUserProperties() {
        var clientContext = new SP.ClientContext.get_current();
        var peopleManager = new SP.UserProfiles.PeopleManager(clientContext);
        userProfileProperties = peopleManager.getMyProperties();
        clientContext.load(userProfileProperties);
        clientContext.executeQueryAsync(onRequestSuccess, onRequestFail);
    }
    function onRequestSuccess() {
        var Bild = userProfileProperties.get_userProfileProperties()['PictureURL']
        document.getElementById("workEmailDiv").innerHTML = userProfileProperties.get_userProfileProperties()['WorkEmail'];
        document.getElementById("prefNameDiv").innerHTML = userProfileProperties.get_userProfileProperties()['PreferredName'];
        document.getElementById("workPhoneDiv").innerHTML = userProfileProperties.get_userProfileProperties()['WorkPhone'];
        document.getElementById("bild").innerHTML = "<img src='" + Bild + "'/><br /><br />";
        // $("#bild").attr('src', Bild); //requires jQuery
    }

    function onRequestFail(sender, args) { alert( args.get_message());}

</script>

<div id="bild"></div>
<b>Name:</b> <div id="prefNameDiv"></div>
<b>Work Email:</b> <div id="workEmailDiv"></div>
<b>Work Phone:</b> <div id="workPhoneDiv"></div>
1
  • Note that, for me to get this to work, I had to add <script type="text/javascript">$(document).ready(function({ getUserProperties()); });</script> and add a reference to jQuery, as well as add a var timer = setTimeout(function() { // put the contents of onRequestSuccess in here... }, 250);. My services were getting the data faster than my page could create the DOM and post it.
    – vapcguy
    Mar 11, 2019 at 22:56
3

On the last bit of code you forgot to declare property. You have properties and then are calling property.Key and property.Value but there is no context to the variable property in the code. I changed it below.

var data = {};
        $.ajax({  
            url: _spPageContextInfo.webAbsoluteUrl + "/_api/SP.UserProfiles.PeopleManager/GetMyProperties",  
            headers: { Accept: "application/json;odata=verbose" },  
            success: function (response) {  
                try {  
                    //Get properties from user profile Json response  
                    data.userDisplayName = response.d.DisplayName;  
                    data.AccountName = response.d.AccountName;
                    data.Title = response.d.Title;  
                    var properties = response.d.UserProfileProperties.results;  
                    for (var i = 0; i < properties.length; i++) {
                        var property = properties[i]; 
                        if (property.Key == "SPS-Department") {  
                            data.Department = property.Value;  
                        }
                        if (property.Key == "SPS-School") {
                            data.School = property.Value;
                        }  
                        if (property.Key == "SPS-Interests") {
                            data.Interests = property.Value;
                        }                             
                        if (property.Key == "SPS-PastProjects") {
                            data.Projects = property.Value;
                        }                             
                        if (property.Key == "SPS-Birthday") {
                            data.Birthday = property.Value;
                        }                             
                        if (property.Key == "AboutMe") {
                            data.AboutMe = property.Value;
                        }                             
                        if (property.Key == "CellPhone") {
                            data.MobilePhone = property.Value;
                        }                             
                        if (property.Key == "PictureUrl") {
                            data.PictureUrl = property.Value;
                        }
                        if (property.Key == "Office")   {
                            data.Office = property.value;
                        }
                    }  

                } catch (err2) {  
                    //console.error(JSON.stringify(err2));  
                }  
            },  
            error: function (jQxhr, errorCode, errorThrown) {  
                console.error(errorThrown);  
            }  
        });
1
  • The only weird thing for me - I populated the "Office" field with a value, then I went back and changed it. This code pulled back the old value for the field, while the ECMAScript in the accepted answer pulled back the current value. Any ideas why and how to get it to pull back the current value?
    – vapcguy
    Mar 11, 2019 at 22:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.