Tuesday, June 9, 2015

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


  1. function getUserById() {
  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.     );
  11.     function ensureUserSuccess() {
  12.         //You can access the properties here
  13.         alert(user.get_title());
  14.         alert(user.get_loginName());
  15.     }
  17.     function onFail() {
  18.         alert('Fail');
  19.     }
  20. }


  1. You can get the user ID with:


  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?

    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.

  3. Hi, Great.. Tutorial is just awesome..It is really helpful for a newbie like me.. I am a regular follower of your blog.
    Really very informative post you shared here. Kindly keep blogging. If anyone wants to become a Front end developer learn from Javascript Online Training from India .
    or learn thru JavaScript Online Training from India. Nowadays JavaScript has tons of job opportunities on various vertical industry. ES6 Training in Chennai