Check If Current User Is Present In A Specific Group Or Not, Using SPServices

In this blog, we will see how to check if the current user is present in specific group or not, using SPServices.

Recently, I faced one situation where I needed to show li element for some specific group of users. For that, we have the below HTML - UL LI structure and from that, we need to show the "Create" link only for admin users (Group Name: Category Owner).
  1. <div>  
  2.     <ul>  
  3.         <li id=”Category1”>Category1</li>  
  4.         <li id=”Category2”>Category1</li>  
  5.         <li id=”Category3”>Category1</li>  
  6.         <li id=”Category4”>Category1</li>  
  7.         <li id=”Category5”>Category1</li>  
  8.         <li id=”Category6”>Category1</li>  
  9.         <li id=”Category7”>Category1</li>  
  10.         <li id=”create”>Create Category</li>  
  11.     </ul>  
  12. </div>  

The above structure is being created on the landing page of my site. Apart from that, I don’t want to show "Create Category" button to all the users. I have created one SharePoint group called “Category Owners” and added users into it.

In document.ready function, I have added the below code to load SPServices.

  1. <script>  
  2.     $(document).ready(function() {  
  3.         insureSPServices(InitializePage);  
  4.     });  
  5.     insureSPServices  
  6.     function is used to make sure SP Services is loaded  
  7.   
  8.     function insureSPServices(callbackFunction) {  
  9.         if ($().SPServices == null) {  
  10.             jQuery.getScript("/_layouts/15/Project /Scripts/jquery.SPServices-0.7.2.js", callbackFunction);  
  11.         } else {  
  12.             callbackFunction.call(null"Already Loaded");  
  13.         }  
  14.     }  
  15.   
  16.     function InitializePage(data, textStatus) {  
  17.         isGroupMember("Category Owners "function(result) {  
  18.             if (result) {  
  19.                 // Code for when current user is in the group  
  20.                 document.getElementById("create").style.display = "block";  
  21.             }  
  22.         });  
  23.     }  
  24.   
  25.     function isGroupMember(groupName, callback) {  
  26.         $().SPServices({  
  27.             operation: "GetGroupCollectionFromUser",  
  28.             userLoginName: $().SPServices.SPGetCurrentUser(),  
  29.             async: false,  
  30.             completefunc: function(xData, Status) {  
  31.                 callback($(xData.responseXML).find("Group[Name='" + groupName + "']").length == 1);  
  32.             }  
  33.         });  
  34.     };  
  35. </script>