Get current user and handle a success callback
By Anatoly Mironov
In my previous post I needed the accound id of the current user for posting new list items. To retrieve the id, we can push this to the client from the code behind, or get the current user using Client Object Model. To provide a more generic way we can write a js function which get the current user. But we must even provide some callback functionality, otherwise we don’t know if the operation was successful or not. Let’s be inspired by success and error properties in $.ajax:
function retrieveCurrentUser(success, error) {
ExecuteOrDelayUntilScriptLoaded(function () {
var ctx = new SP.ClientContext.get\_current();
var web = ctx.get\_web();
ctx.load(web);
var user = web.get\_currentUser();
user.retrieve();
ctx.executeQueryAsync(function () {
success(user);
}, function (data) {
error(data);
});
}, "SP.js");
}
```Then success function can receive the user account like:
function doSomething(user) { console.log(“user name: " + user.get_loginName()); } function errorCallback(data) { console.log(“hmpf, didn’t work, why?”); } retrieveCurrentUser(doSomething, errorCallback);
##### EDIT
If you just need current user id, as I needed, there is actually a better way. [I saw a solution for another problem in sharepoint.stackexhange](http://sharepoint.stackexchange.com/questions/6915/get-the-current-ui-language-with-ecmascript "It was a question about how to get the current language") and found this:
var userid = _spPageContextInfo.userId;
[![](https://sharepointkunskap.files.wordpress.com/2011/12/sppagecontextinfo.png "sppagecontextinfo")](https://sharepointkunskap.files.wordpress.com/2011/12/sppagecontextinfo.png) More background information about \_spPageContextInfo can be found on [Ted Pattison's blog](http://blog.tedpattison.net/Lists/Posts/Post.aspx?ID=9). The userId of ther current user can be got through:
var userid = _spUserId;