Today I was asked how to retrieve all of the SharePoint Groups of the currently logged-in user to sharepoint.
To achieve this, first you need to recover the authority connected to sharepoint with the function GetCurrentUser and then read the “ID” property. Once you have this, you can then use the GetGroupsOfUser (userId) that takes as input the user “ID”. GetGroupsOfUser function returns all of the groups in where the “Title” property can be extracted.
function GetCurrentUser () { var requestUri = "hhtp://mysite/_api/web/CurrentUser/"; // execute AJAX request return $.ajax({ url: requestUri, type: "GET", headers: { "ACCEPT": "application/json;odata=verbose" } }); } function GetGroupsOfUser (userId) { var requestUri = "hhtp://mysite/_api/web/GetUserById(" + userId + ")/Groups"; // execute AJAX request return $.ajax({ url: requestUri, type: "GET", headers: { "ACCEPT": "application/json;odata=verbose" } }); }
Here’s a way to make calls to functions :
$.when(GetCurrentUser()).done(function (data) { $.when(GetGroupsOfUser (data.d.Id)).done(function (groups) { $.each(groups.d.results, function(i, result) { //result.Title is the name of the group console.log(result.Title); }); }); });