How to read SharePoint 2013 User Profile using JSOM

Home | SharePoint 2013 | How to read SharePoint 2013 User Profile using JSOM

In this article i ‘b be dealing with how to read SharePoint 2013 User Profile properties using Javascript Object Model (JSOM). We know that SharePoint 2013 provides JSOM support for User Profile properties.

Create a SharePoint Hosted App and call it as ‘Read User Profile’

Go to Default.aspx in the SP Hosted App and add the references to SP.UserProfile.Js in the PlaceHolderAdditionalPageHead.

<script type="text/javascript" src="/_layouts/15/SP.UserProfiles.js"></script> 

It will already have references to SP.UserProfile.js and App.js

<script type="text/javascript" src="/_layouts/15/sp.js"></script>
<script type="text/javascript" src="../Scripts/App.js">

Open the App.JS and replace its current code with the following code

var personProperties;
// This code runs when the DOM is ready and creates a context object which is needed to use the SharePoint object model
$(document).ready(function () {
    //    getUserName();
   
    SP.SOD.executeOrDelayUntilScriptLoaded(getUserProperties, ‘SP.UserProfiles.js’);
   
});

function getUserProperties() {

   
    //set your user id, the following format is the user id for Office 365. If you are reading it from SharePoint OnPremise assign user id in the DomainUserId
    var targetUser = “i:0#.f|membership|UserID@SharePointSite.onmicrosoft.com”;

    //Instantiate Client Context
    var clientContext = new SP.ClientContext.get_current();

    //Instantiate People Manager
    var peopleManager = new SP.UserProfiles.PeopleManager(clientContext);

    // Get the instance of person properites
        personProperties = peopleManager.getPropertiesFor(targetUser);

    // Load the PersonProperties object and send the request.
    clientContext.load(personProperties);
    clientContext.executeQueryAsync(onRequestSuccess, onRequestFail);
}

// This function runs if the executeQueryAsync call succeeds.
function onRequestSuccess() {

    // Get a property directly from the PersonProperties object.
    var messageText = ” “LastName is ” property is “
        + personProperties.get_userProfileProperties()[‘LastName’];

    // Get a property from the UserProfileProperties property.
    messageText += “<br />”WorkPhone Number” property is “
        + personProperties.get_userProfileProperties()[‘WorkPhone’];
    $get(“results”).innerHTML = messageText;
}

// This function runs if the executeQueryAsync call fails.
function onRequestFail(sender, args) {
    $get(“results”).innerHTML = “Error: ” + args.get_message();
}

Set the following permissions

app permission

ReadUserProfile

 

 Subscribe to my blog

 

 

Leave a Reply