SharePoint Online – Getting current logged-in user’s group details using REST api and JavaScript

Introduction:

Hi All,

Today we will discuss how we can fetch current logged-in user’s group details using REST api and JavaScript. SharePoint provides a REST endpoint for fetching user and group details at the web level (below snippet).

Let’s see how we can use this endpoint.

REST endpoint:

<Site URL>/_api/web/getuserbyid("<user id>")/Groups

Note: We can get current sign-in user information such as Title, Email etc from “_spPageContextInfo” without any REST call. But here we will see how we can retrieve user and group details using REST endpoint.

HTML Mark-up:

Create a JavaScript or HTML file and add the HTML mark-up as per the requirement. In my case I have a header, 3 paragraph tags and a table for showing groups.

<h2>User Details| JQuery & REST Api</h2>

<p id="title"></p>
<p id="email"></p>
<p id="isAdmin"></p>
<table id="tbl" border="0" cellpadding="5px" cellspacing="0"></table>

jQuery Library:

Add jQuery library to the file. I’m using a jQuery CDN reference here but if you are in production environment, then upload the jQuery library to site asset and use it instead of CDN.

<!-- JQuery library -->
<script src="https://code.jquery.com/jquery-1.12.4.min.js" type="Text/JavaScript"></script>

JavaScript / jQuery Code:

Once our DOM and library is added to the file, add functions and variables as per requirement. Define a function named  “GetCurrentUserInfo” with variables for REST URI, request header, content type and Ajax function.

I’ve used “_spPageContextInfo.webAbsoluteUrl” instead of hard coding the URL for making code dynamic.

// GetCurrentUserInfo
var GetCurrentUserInfo = function(param){

	// Rest endpoint for user information.
	var requestUri = _spPageContextInfo.webAbsoluteUrl + "/_api/web/getuserbyid(" + param + ")/Groups";
	
	// header and content type
	var _requestHeader = { "accept" : "application/json;odata=verbose" };
	var _contentType = "application/json;odata=verbose";
	
	// jQuery Ajax Call
	$.ajax({
		url : requestUri,
		async: false,
		contentType : _contentType,
		headers : _requestHeader,
		success : onSuccessFunc,
		error : onErrorFunc
	});

}; // GetCurrentUserInfo() Ends

Now, define a function named “onSuccessFunc” which will be executed upon successful execution of Ajax call. Here, we will bind the retrieved results to the HTML DOM.

var onSuccessFunc = function(data, request){
   
   // Show current user information from _spPageContextInfo
   document.getElementById("title").innerHTML = "<b>Name of user : </b>"+_spPageContextInfo.userDisplayName;
   document.getElementById("email").innerHTML = "<b>E-Mail ID : </b>"+_spPageContextInfo.userEmail;
   document.getElementById("isAdmin").innerHTML = "<b>Is Site Collection Admin : </b>"+_spPageContextInfo.isSiteAdmin;

   var res = "";
   // loop through the response
   $.each(data.d.results,function(index,value){
     res +="<tr><td>"+(index+1)+"</td><td>"+value.Title+"</td></tr>";
   });
   // bind to the table.
   document.getElementById("tbl").innerHTML = res;
};

Now, the error handling. Define a function named as “onErrorFunc” which will be executed upon execution failed for some reason.

var onErrorFunc = function(error, msgResp){
   var errorMessage = "Error Occured!\n------------------------------\n-> Status   : "+ error.status+"\n-> Message : "+error.statusText;
   alert(errorMessage);
   console.log(errorMessage);
};

Note for beginners: Error handling is extremely important part of development process. If the error handling is not implemented properly, it’s makes issues harder to detect. Its very easy to make such mistake in JavaScript because there is no compiler.

Execute the function:

Now, execute the function on document ready. Here, under document ready I obtained user id from “_spPageContextInfo” and pass it to the GetCurrentUserInfo() function as parameter.

// Document ready function.
$(document).ready(function(){
	
  // Get the user ID from _spPageContextInfo.
  var userid = _spPageContextInfo.userId;
	
  // Call the function and pass user id collected from _spPageContextInfo
  var result = GetCurrentUserInfo(userid);
	
});
// Document ready Ends.

Result:

Now, once the JavaScript or HTML file is ready, then

  1. upload the file to site assets or any library.
  2. Edit the web part page we have created and add content editor web part to the page.
  3. On the content editor web part add the reference link to the js/html page.

Fig 1: SharePoint Online – Demo – Showing groups Result using REST API

Thanks for reading 🙂

Keep reading, share your thoughts, experiences. Feel free to contact us to discuss more. If you have any suggestion / feedback / doubt, you are most welcome.

Stay tuned on Knowledge-Junction, will come up with more such articles

You may also like...

1 Response

  1. Manoj Sutar says:

    goodone

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: