Thursday, October 26, 2017

Get Logged in user details in SharePoint 2013 using REST

I have seen lot of SharePoint Developer need to know the details of Logged in User on Client Side. if you are developing custom webpart its very easy where you have to code to get the details and store in the JavaScript variables.

The things gets little tricky when you want these details in the client side only. like content Editor webpart where you are not going with the Custom solutions.

There are 2 ways, either you can use JSOM or REST service.

In my first example i already shown how to use JSOM. here is another way to use REST to get the details of logged in SharePoint 2013 User.


  • Create a getUser.Js file
  • add following on load jscript code to give a call to getUserName function
$(document).ready(function () {

// Load SP.js file before calling JSOM code
// On Publishing pages SP.js loads automatically
SP.SOD.executeFunc('sp.js', 'SP.ClientContext', getUserName);

});
    • Add below code which will call REST code 
      function getUserName()
      {
      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){
          userdisplayname = data.d.Title; // You can use console.log(data) to get other properties
      }

      function onError(error) {
          alert("User name not found, you may experience some data issues in some applications");
      }

    • Uppload getUser.js file to style library (or any other library you want).
    • Add getUser.js file on page using Content Editor WebPart
    • Make sure your Content Editor HTML is as below
    Note:


    • SP.js is only loaded on Demands in some pages.

    No comments: