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:

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.

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.

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.

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.

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

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.

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

Advertisements

Comments

One comment on “SharePoint Online – Getting current logged-in user’s group details using REST api and JavaScript”
  1. Manoj Sutar says:

    goodone

Leave a Reply

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