Friday, 15 September 2017

Add user to SharePoint Group using REST API

Rest being powerful api in SharePoint now, we can do most of the operations using REST api, below is the function to add user to SharePoint group.




Usage : AddUsertoGroup("userLoginName", "GroupID");

this function will return the user id, which can be used for further processing.


function AddUsertoGroup(userLoginName, GroupID) {
var useridval = "";
$.ajax({
url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/sitegroups(" + GroupID + ")/users",
type: "POST",
async: false,
contentType: "application/json;odata=verbose",
data: JSON.stringify({
'__metadata': {
'type': 'SP.User'
},
'LoginName': userLoginName
}),
headers: {
"Accept": "application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val()
},
success: function(data) {
useridval = data.d.Id;
},
error: function(data) {
console.log(data);
}
});
return useridval;
}

No comments:

Post a Comment