Monday, January 4, 2016

Get Logged-In User using SPServices


This blog shows the snipped to get Logged-In User using SPServices. This is a very common task which comes in our projects.
var userAccount = $().SPServices.SPGetCurrentUser({
          fieldName: "Title", 
          debug: false
});
Here "Title" will give you Display Name of the user. If you will user "Name" as fieldName, you will get logged in user name but in the claims-based format i.e. i:0#.w|User_Name.
Another way of getting Logged-In User is :-
$().SPServices({
operation: "GetUserInfo",
async: false,
userLoginName: $().SPServices.SPGetCurrentUser(),
completefunc: function (xData, Status) {
 $(xData.responseXML).find("User").each(function() {
 
       curUserId = $(this).attr("ID"); 
       curUserName = $(this).attr("Name"); 
       curFullUserName = $(this).attr("ID")+";#"+$(this).attr("Name"); 
        });
     }
});
The below code shows code-snippet of - "How to check Logged-In User in a SharePoint Group":-
<script type="text/javascript" src="/sites/<Site_URL>/jquery-1.7.2.min.js"></script>
<script type="text/javascript" src="/sites/<Site_URL>/jquery.SPServices-0.7.2.min.js"></script>
 
<script type="text/javascript">
$( document ).ready(function() {
 var userName = $().SPServices.SPGetCurrentUser();
 $().SPServices({
 operation: "GetGroupCollectionFromUser", 
 userLoginName: userName,
 async: false,
 completefunc: function (xData, Status) { 
 if ($(xData.responseXML).find("Group[Name='Site Owners']").length == 1) {
      //alert("login inside of the Group user");
 }
 else {
      //alert("login outside of the Group user");  
 }
 }//End of completefunc
 });//End SPServices
});//End Doc Ready
</script>

No comments:

Post a Comment