Tuesday, June 9, 2015

How to get SharePoint User by User Id in JavaScript using JSOM

Solution

  1. function getUserById() {
  2.  
  3.     var context = new SP.ClientContext.get_current();
  4.     var user = context.get_web().get_siteUsers().getById('1073741823');//Give the user id here
  5.     context.load(user);
  6.     context.executeQueryAsync(
  7.          Function.createDelegate(null, ensureUserSuccess),
  8.          Function.createDelegate(null, onFail)
  9.     );
  10.  
  11.     function ensureUserSuccess() {
  12.         //You can access the properties here
  13.         alert(user.get_title());
  14.         alert(user.get_loginName());
  15.     }
  16.  
  17.     function onFail() {
  18.         alert('Fail');
  19.     }
  20. }

3 comments:

  1. You can get the user ID with:

    _spPageContextInfo.userId

    ReplyDelete
  2. Thanks for the elegant code.
    Unfortunately for me (using SP 2013 on prem) it only works when I EDIT the page on which the content is displaying. If I simply view the page (not in EDIT mode) I get "Unable to get property 'get_current' of undefined or null referenceTypeError" in IE or "SP.ClientContext is undefined" in Firefox.
    I've tried all the preloading sp.js and SP.ClientContext suggestions to no change in results.
    Is there some permission requirement?

    ReplyDelete
    Replies
    1. On some times of pages, SP2013 only loads the necessary JS library when the page is in edit mode. Maddening, right? You need to do something like this to force it to load:

      SP.SOD.executeFunc('sp.js', 'SP.ClientContext', function(){});//force load our sp.js
      SP.SOD.executeOrDelayUntilScriptLoaded(getUserById,"sp.js");//for some bizarre reason it doesn't always work right if you just use the first one; thus, the second.

      Though it might be a different file called SP.UserProfile or some such, can't rightly remember.

      Delete