Pages

Monday, September 28, 2015

Get SharePoint Site Users and User Profiles using JSOM


Using SharePoint JavaScript Client Side Object Model framework, we can get all site users information and each user profile properites (ex. Birthday, Work Email, Phone...etc).

1. To get site users information, use SP.Web.siteUsers property
2. then use SP.UserProfiles.PeopleManager.getUserProfilePropertyFor Method to get user profile properties.

Example code:

//Usage
var scriptbase = _spPageContextInfo.webAbsoluteUrl + '/_layouts/15/';
$.getScript(scriptbase + 'SP.js', function () {
  $.getScript(scriptbase + 'SP.UserProfiles.js', function () {
    getUsersBirthdays(function(usersProperties){
       for(var i = 0; i < usersProperties.length;i++)
       {
           console.log(usersProperties[i].get_value());
       }
    },
    function(sender,args){
       console.log(args.get_message());
    });
  });
});

//Get Birthday User Profile Property for Site Users
function getUsersBirthdays(Success,Error) {
    var clientContext = new SP.ClientContext.get_current();
    var web = clientContext.get_web();

    var users = web.get_siteUsers();
    clientContext.load(users);
    clientContext.executeQueryAsync(
    function() {
       var peopleManager = new SP.UserProfiles.PeopleManager(clientContext);
       var personsProperties = [];
       for(var i = 0; i < users.get_count();i++)
       {
           var user = users.getItemAtIndex(i);
           var personBirthday = peopleManager.getUserProfilePropertyFor(user.get_loginName(),'SPS-Birthday');
           personsProperties.push(personBirthday);
       }

       clientContext.executeQueryAsync(
           function() {
             Success(personsProperties);
           },
           Error);

    },
    Error);
}



1 comment:

  1. Thanks, saved my time. Handling both getting users and user profile properties of each user is excellent. I was facing issue in getting both together but your solution made my day. Thanks again.

    ReplyDelete