Thursday, 12 June 2014

Different ways to get user name using javascript

Get user email

_spPageContextInfo.userLoginName

Using REST Service

 $(document).ready(function () {  
 var userid = _spPageContextInfo.userId;  
 function GetCurrentUser() {  
 var requestUri = _spPageContextInfo.webAbsoluteUrl + "/_api/web/getuserbyid(" + userid + ")";  
 var requestHeaders = { "accept" : "application/json;odata=verbose" };  
 $.ajax({  
  url : requestUri,  
  contentType : "application/json;odata=verbose",  
  headers : requestHeaders,  
  success : onSuccess,  
  error : onError  
 });  
 }  
 function onSuccess(data, request){  
  //var loginName = data.d.LoginName.split('|')[1];  
  var loginName = data.d.Title; 
  alert(loginName);  
 }  
 function onError(error) {  
  alert(error);  
 }  
 GetCurrentUser();  
 });  

Using JSOM

 $(document).ready(function () {   
 var currentUser;  
 // Ensure that the SP.js is loaded  
 if (SP.ClientContext != null) {  
  SP.SOD.executeOrDelayUntilScriptLoaded(getCurrentUser, 'SP.js');  
 }  
 else {  
  SP.SOD.executeFunc('sp.js', null, getCurrentUser);  
 }  
 function getCurrentUser() {  
  var context = new SP.ClientContext.get_current();  
  var web = context.get_web();  
  currentUser = web.get_currentUser();  
  context.load(currentUser);  
  context.executeQueryAsync(onSuccessMethod, onRequestFail);  
 }  
 function onSuccessMethod(sender, args) {  
  var account = currentUser.get_loginName();  
  var currentUserAccount = account.substring(account.indexOf("|") + 1);  
  alert(currentUserAccount);  
 }  
 // This function runs if the executeQueryAsync call fails.  
 function onRequestFail(sender, args) {  
  alert('request failed' + args.get_message() + '\n' + args.get_stackTrace());  
 }  
 });  

No comments:

Post a Comment