Retrieving SP user info using Client Object Model
September 26, 2012 5 Comments
Recently I built a visual web part to show current user’s information (Picture, Name, etc). Instead of using SharePoint server object model, this time I choose to use client OM. First I need to get the id of the logged-in user, which can be retrieved from _spPageContextInfo.userId (Ted Pattison has posted an excellent article explaining this variable). Next step is to get the client context.
var context = new SP.ClientContext.get_current(); var web = context.get_web(); var userInfoList = web.get_siteUserInfoList(); var camlQuery = new SP.CamlQuery(); camlQuery.set_viewXml('<View><Query><Where><Eq><FieldRef Name=\'ID\' />' + '<Value Type=\'Number\'>' + userId + '</Value></Eq>' + '</Where></Query><RowLimit>1</RowLimit></View>'); this.userListItem = userInfoList.getItems(camlQuery); context.load(this.userListItem); context.executeQueryAsync( Function.createDelegate(this, onSucceeded), Function.createDelegate(this, onFailed));
The onSucceeded function is called when the query runs successfully, otherwise the onFailed function will be executed.
function onSuceeded(sender, eventArgs) { var item = this.userListItem.itemAt(0); var name = item.get_item('Name'); var userName = "Name"; if (name) { userName = name; } alert(userName); }
One last thing to remember is to run the code after SP.js is loaded
SP.SOD.executeOrDelayUntilScriptLoaded(LoadUserInfo, 'SP.js');
Nice post. I have done this like this, until I found another js function from SharePoint API: web.get_currentUser. There you don’t need any caml queries anymore.
That makes it a lot simpler :)…didn’t know that method exists, cheers for that.
The difference here is that Anatoly’s code gets only the current user. The original example can be supplied with ANY user to get there name. Is that correct?
If you’re interested to get other users information then yes but if you want to quickly retrieving current user’s info then Anatoly’s code is a lot simpler.
Do you have an example of how to get the user info if you have a login id or name? This works great if you happen to know the number of the user. This isn’t available typically.