SharePoint 2013 – Get Current User LoginName using JSOM & REST

Using SharePoint 2013 REST Service

$(document).ready(function () {

var userid = _spPageContextInfo.userId;

function GetCurrentUser() {
var requestUri = _spPageContextInfo.webAbsoluteUrl + "/_api/web/getuserbyid(" + userid + ")";

var requestHeaders = { "accept" : "application/json;odata=verbose" };

$.ajax({
  url : requestUri,
  contentType : "application/json;odata=verbose",
  headers : requestHeaders,
  success : onSuccess,
  error : onError
});
}

function onSuccess(data, request){
  var loginName = data.d.LoginName.split('|')[1];
  alert(loginName);
}

function onError(error) {
  alert(error);
}

GetCurrentUser();

});

Using SharePoint 2013 JSOM

$(document).ready(function () { 

var currentUser;
// Ensure that the SP.js is loaded
if (SP.ClientContext != null) {
  SP.SOD.executeOrDelayUntilScriptLoaded(getCurrentUser, 'SP.js');
}
else {
  SP.SOD.executeFunc('sp.js', null, getCurrentUser);
}

function getCurrentUser() {
  var context = new SP.ClientContext.get_current();
  var web = context.get_web();
  currentUser = web.get_currentUser();
  context.load(currentUser);
  context.executeQueryAsync(onSuccessMethod, onRequestFail);
}

function onSuccessMethod(sender, args) {
  var account = currentUser.get_loginName();
  var currentUserAccount = account.substring(account.indexOf("|") + 1);
  alert(currentUserAccount);
}
// This function runs if the executeQueryAsync call fails.
function onRequestFail(sender, args) {
  alert('request failed' + args.get_message() + '\n' + args.get_stackTrace());
}

});

Conclusion:Ā 

I would suggest using REST since it does not require SP.js to be loaded.

SP.js is only loaded on demand in some pages.

Advertisements

13 thoughts on “SharePoint 2013 – Get Current User LoginName using JSOM & REST

  1. I was very happy to uncover this great site. I want to
    to thank you for ones time due to this fantastic read!!
    I definitely liked every bit of it and i also have you book-marked
    to look at new stuff on your blog.

  2. Here is another approach to the REST call:

    $.ajax({
    url: “/sites/mysite/_api/web/currentUser”,
    type: “GET”,
    headers: { “Accept”: “application/json;odata=verbose” },
    success: function (data) {

    //Get the user ID
    var userID = data.d.Id;

    },
    error: function (data) {
    //output error HERE
    alert(data.statusText);
    }
    });

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s