In this blog, we will learn about how to add users to a SharePoint site, using JSOM
Kindly find the code given below in order to achieve this feat. The code creates two text fields & a button in the SharePoint page, where you are going to add JS.
- User to be added (Fill in the username, who needs to be added).
- Sharepoint Group Name (Fill SharePoint group name, where the users are required to be added).
- Add User- Once the fields given above have been filled, click on the Add User button in order to add the user to the particular SharePoint group.
On the operation's success, you will get an alert 'success' and on error, you will get an alert 'Request failed.'
- <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
- <html> User to be added: <input type="text" id="name" /><br> <br> Sharepoint Group Name : <input type="text" id="groupName" /><br> <br> <br> <input type='button' value='Add User' onclick="AddUserToSharePointGroup();" />
-
- </html>
- <script language="javascript" type="text/javascript">
- var user;
- var spGroup;
-
- function AddUserToSharePointGroup() {
- var clientContext = new SP.ClientContext.get_current();
- var siteGroups = clientContext.get_web().get_siteGroups();
- var web = clientContext.get_web();
- spGroup = siteGroups.getByName(document.getElementById('groupName').value);
- user = web.ensureUser(document.getElementById('name').value);
- var userCollection = spGroup.get_users();
- userCollection.addUser(user);
- clientContext.load(user);
- clientContext.load(spGroup);
- clientContext.executeQueryAsync(onQuerySucceeded, onQueryFailed);
- }
-
- function onQuerySucceeded() {
- alert('success');
- }
-
- function onQueryFailed() {
- alert('Request failed.');
- }
- </script>