Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SharePoint 2013 get current user using JavaScript

How to get current user name using JavaScript in Script Editor web part?

like image 549
Kate Avatar asked Jan 07 '14 20:01

Kate


People also ask

How to get current user login name in SharePoint using JavaScript?

Get Current SharePoint User Login Name Using JSOM You can use the “get_loginName()” to get the current login name using JSOM.

Can you use JavaScript in SharePoint?

You can update your SharePoint site's UI by using JavaScript. This extensibility option is only available for classic SharePoint experiences.

What is _spPageContextInfo?

_spPageContextInfo variable is used when you are working with JavaScript Object Model. Create a WebPart page and add a Script Editor Web part in it. You can use below snippet in your code to access _spPageContextInfo properties. More properties are listed in section below.


2 Answers

Here is the code that worked for me:

<script src="/SiteAssets/jquery.SPServices-2013.02a.js" type="text/javascript"></script> <script src="/SiteAssets/jquery.js" type="text/javascript"></script>  <script type="text/javascript">   var userid= _spPageContextInfo.userId;   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.Title;     alert(loginName);   }    function onError(error) {     alert("error");   } </script> 
like image 62
Kate Avatar answered Oct 07 '22 17:10

Kate


I found a much easier way, it doesn't even use SP.UserProfiles.js. I don't know if it applies to each one's particular case, but definitely worth sharing.

//assume we have a client context called context. var web = context.get_web(); var user = web.get_currentUser(); //must load this to access info. context.load(user); context.executeQueryAsync(function(){     alert("User is: " + user.get_title()); //there is also id, email, so this is pretty useful. }, function(){alert(":(");}); 

Anyways, thanks to your answers, I got to mingle a bit with UserProfiles, even though it is not really necessary for my case.

like image 44
Mzn Avatar answered Oct 07 '22 17:10

Mzn