Wednesday, April 30, 2014

How to Get Current Logged in User and Display Name using SharePoint 2013 REST API?



In this post we will discuss how to get current logged in user and display name using SharePoint 2013 REST API.

Also you can check out:

- Prevent new sites to be added to content databases in SharePoint 2013

- Steps to create App Catalog site in SharePoint 2013

- SharePoint 2013 list column status wise Change row Color using jQuery

REST API is quite simple and straightforward, used User ID to get user Title, Email for SharePoint 2013 and apps for SharePoint. use  /_api/web/getuserbyid(ID) to get the user field  in the response data, we have an “AuthorId” will get us the user Title, Email etc .


Step-1: Navigate to your SharePoint 2013 site and create a Wiki Page or a Web Parts page.

Step-2: The process to add your JavaScript code is quite straightforward:
Edit the page, go to the “Insert” tab in the Ribbon and click the “Web Part” option. In the “Web Parts” picker area, go to the “Media and Content” category, select the “Script Editor” Web Part and press the “Add button”.

Step-3: Once the Web Part is inserted into the page, you will see an “EDIT SNIPPET” link click. You can insert the HTML and/or JavaScript code into the dialog.


<script src="/Style Library/scripts/jquery-1.10.1.min.js"></script>
<script type="text/javascript">
  var userid= _spPageContextInfo.userId;
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 Logg = data.d;

    //get login name
    var loginName  = Logg.LoginName.split('|')[1];
    alert(loginName);   
    //get display name
    alert(Logg.Title);

}

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

</script>

In the code above, we'll get the author id from the list. By passing the author id in to GetUserBuId() method, it will return the user in raw format like "I:O#.f|xxxx|xx@xxxx.com". We can get the login name by splitting the output.



1 comments:

Alexander Zoutenbier said...

Hi Bijay,

I tested your script, it's working but why you would use something like this?

Regards, Alex

Post a Comment

Twitter Delicious Facebook Digg Favorites More