Editor’s note: Contributor Tahir Naveed is a Microsoft SharePoint Specialist in the New York City region
Within an organization, users are created in an Active Directory and then imported to SharePoint through the User Profile Service. This service creates User Profiles in SharePoint which have properties like name, email, phone number, manager etc as well as some custom properties.
The following script will access four User Profile properties (Title, Department, Office location and Phone) through the JavaScript Object Model:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 |
<script src="/_layouts/15/jquery-1.9.1.min.js" type="text/javascript"></script> <script src="/_layouts/15/Scripts/MicrosoftAjax.js" type="text/javascript"></script> <script src="/_layouts/15/init.js" type="text/javascript"></script> <script src="/_layouts/15/sp.runtime.js" type="text/javascript"></script> <script src="/_layouts/15/sp.js" type="text/javascript"></script> <script src="/_layouts/15/SP.UserProfiles.js" type="text/javascript"></script> <script type="text/javascript"> //$(document).ready(function(){ 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); } // This function runs if the executeQueryAsync call succeeds. function onRequestSuccess() { var messageText = "<b>"; if (userProfileProperties.get_userProfileProperties()['Title'] != "") messageText += userProfileProperties.get_userProfileProperties()['Title']; if (userProfileProperties.get_userProfileProperties()['SPS-Department'] != "") messageText += ", " + userProfileProperties.get_userProfileProperties()['SPS-Department']; if (messageText.length > 5) messageText += "<br/>"; if (userProfileProperties.get_userProfileProperties()['Office'] != "") messageText += userProfileProperties.get_userProfileProperties()['Office']; if (userProfileProperties.get_userProfileProperties()['WorkPhone'] != "") messageText += ", " + userProfileProperties.get_userProfileProperties()['WorkPhone']; messageText += "</b>"; $get("results").innerHTML = messageText; } // This function runs if the executeQueryAsync call fails. function onRequestFail(sender, args) { $get("results").innerHTML = "Error: " + args.get_message(); } </script> <div id="results"> </div> |
Example:
1. Create a blank ASPX page.
2. Add a Content Editor Web Part to the page.
3. Copy the above JavaScript on the page to get the following output
Ref1: http://technet.microsoft.com/en-us/library/ee721054.aspx
Ref2: http://technet.microsoft.com/en-us/library/hh147510.aspx