Saturday, 22 November 2014

SharePoint 2013/Online: Get current logged in user's groups using javascript

This Post explains how to get current logged in users Groups using javascript. Its a simple ajax call to the sharepoint service. Use the below code

$(document).ready(function () {
     var userid = _spPageContextInfo.userId;
getCurrentUserGroups(userid);
});
function getCurrentUserGroups(UserID) {
    $.ajax({
        url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/GetUserById(" + UserID + ")/Groups",
        type: "GET",
        headers: { "Accept": "application/json; odata=verbose", "X-RequestDigest": $("#__REQUESTDIGEST").val() },
        dataType: "json",
        async: true,
        success: function (data) {
            /* get all group's title of current user. */
            var results = data.d.results;
            for (var i = 0; i < results.length; i++) {
               alert(results[i].Title);
            }
        }
    });
}