Introduction
In this blog, let’s explore the easy way to get current user group collection through REST API in JQuery.
Initially we have to obtain the current user of SharePoint group they belong to, which can be achieved using SharePoint 2013 REST API.
Let's proceed
When we use /_api/web/CurrentUser and /_api/web/GetUserById("+UserID+")/ Groups , we get the current user’s group collection . Right now I am using a work around that iterates through the (big) result set. To get the group for the current Login User follow below steps.
Step 1: Navigate to your SharePoint 2013 site.
Step 2: From this page select the Site Actions | Edit Page.
Edit the page, go to the "Insert" tab in the Ribbon and click the "Web Part" option. In the "Web Parts" dialogue, go to the "Media and Content" category, select the "Script Editor" Web Part and click the "Add button".
Step 3: Once the Web Part is inserted into the page, you will see an "EDIT SNIPPET" link; click it. You can insert the HTML and/or JavaScript as in the following.
- <script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.10.1.min.js"></script>
- <script type="text/javascript">
- $(document).ready(function ()
- { getCurrentUser(); });
- function getCurrentUser()
- {
- getUserWebPermissionREST();
- $.ajax({
- url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/CurrentUser",
- method: "GET",
- headers: { "Accept": "application/json; odata=verbose" },
- success: function (data)
- {
- getCurrentUserGroupColl(data.d.Id);
- },
- error: function (data)
- {
- failure(data);
- }
- });
- }
- function getCurrentUserGroupColl(UserID)
- {
- $.ajax
- ({
- url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/GetUserById(" + UserID + ")/Groups",
- method: "GET",
- headers: { "Accept": "application/json; odata=verbose" },
- success: function (data) {
-
- var results = data.d.results; var InnrHtmlgrp = "
- <ul>";
- for (var i = 0; i < results.length; i++)
- {
- InnrHtmlgrp += "
- <li>" + results[i].Title + "</li>";
- }
- $("#Group").append(InnrHtmlgrp + "
- </ul>");
- }
- });
- }
- </script>
- <strong>security Group Name:</strong>
- <div id="Group"></div>
Final Output Result