How to get SharePoint User by User Id in JavaScript using JSOM
Solution
- function getUserById() {
-
- var context = new SP.ClientContext.get_current();
- var user = context.get_web().get_siteUsers().getById('1073741823');//Give the user id here
- context.load(user);
- context.executeQueryAsync(
- Function.createDelegate(null, ensureUserSuccess),
- Function.createDelegate(null, onFail)
- );
-
- function ensureUserSuccess() {
- //You can access the properties here
- alert(user.get_title());
- alert(user.get_loginName());
- }
-
- function onFail() {
- alert('Fail');
- }
- }
You can get the user ID with:
ReplyDelete_spPageContextInfo.userId
Thanks for the elegant code.
ReplyDeleteUnfortunately 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?
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:
DeleteSP.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.