How to Get the Current Logged in User and Display Name Using SharePoint 2013 REST API

Posted: July 20, 2014 in SharePoint2013

Introduction

This article explores with the REST API a quite simple and straightforward way to use a User ID to get the user’s Title and 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” to get the user’s Title, Email and so on.

API

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.

JavaScript code

    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”);

    }

In the code above, we’ll get the author id from the list. By passing the author id into the 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.

output
Advertisements
Comments
  1. Enid says:

    Excellent post. Keep writing such kind of info on your site.
    Im really impressed by your site.
    Hey there, You’ve performed a great job.
    I’ll certainly digg it and in my opinion recommend to my friends.
    I’m sure they’ll be benefited from this web site.

  2. Louis Dembek says:

    Aw, this was a very good post. Spending some time and actual effort to create a top notch article… but what can I say… I put things off a whole lot and never manage to get anything done.

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