How To Add Users In A SharePoint Group Using JSOM

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.'
  1. <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>  
  2. <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();" />  
  3.   
  4. </html>  
  5. <script language="javascript" type="text/javascript">  
  6.     var user;  
  7.     var spGroup;  
  8.   
  9.     function AddUserToSharePointGroup() {  
  10.         var clientContext = new SP.ClientContext.get_current();  
  11.         var siteGroups = clientContext.get_web().get_siteGroups();  
  12.         var web = clientContext.get_web();  
  13.         spGroup = siteGroups.getByName(document.getElementById('groupName').value);  
  14.         user = web.ensureUser(document.getElementById('name').value);  
  15.         var userCollection = spGroup.get_users();  
  16.         userCollection.addUser(user);  
  17.         clientContext.load(user);  
  18.         clientContext.load(spGroup);  
  19.         clientContext.executeQueryAsync(onQuerySucceeded, onQueryFailed);  
  20.     }  
  21.   
  22.     function onQuerySucceeded() {  
  23.         alert('success');  
  24.     }  
  25.   
  26.     function onQueryFailed() {  
  27.         alert('Request failed.');  
  28.     }  
  29. </script>  

 

Ebook Download
View all
Learn
View all