Friday, August 8, 2014

Client Side Scripting: Get Sharepoint User Profile properties using jQuery

In Sharepoint 2010 environment, I recently had a request to fetch the UserProfile object using client side scripting on a Sharepoint page. Immediately, I started looking for any methods exposed within the jQuery library to do so. A jQuery script library called SPServices is available which abstracts SharePoint's Web Services and makes them easier to use.

SPServices: http://spservices.codeplex.com/


Specifically they have examples on how to retrieve UserProfile properties using SPServices library function GetUserProfileByName.


http://spservices.codeplex.com/wikipage?title=GetUserProfileByName


For my own implementation, I modularized the code for fetching the user profile object into a separate javascript file as below:



function returnUserProfile()
{
var user = {};
$().SPServices({
operation: "GetUserProfileByName",
async: false,
AccountName: $().SPServices.SPGetCurrentUser(),
completefunc: function (xData, Status) {
$(xData.responseText).SPFilterNode("PropertyData").each(function() {
              user[$(this).find("Name").text()] = $(this).find("Value").text();
           });        
    }
    });
return user;
}


I can quickly surface the function call in any CEWP/HTML form web part and read the user profile property.

Example: (Redirect based on Users Office location)

var user = {};
var url = document.url + "/sites/region/";
user = returnUserProfile();
window.location.replace(url+user.Office); 


A complete list of all properties available under UserProfile is below:

http://technet.microsoft.com/en-us/library/hh147510%28v=office.15%29.aspx


Hope this helps!

No comments:

Post a Comment