0

I am trying to get details of logged In user through JSOM in SharePoint online.

Below is the code which I am trying:

SP.SOD.registerSod('sp.js', "/_layouts/15/sp.js");
SP.SOD.executeFunc('sp.js', 'SP.ClientContext', getCurrentUser);

function getCurrentUser() {
    try {
        var clientContext = new SP.ClientContext.get_current();
        var tempcurrentUser = clientContext.get_web().get_currentUser();
        clientContext.load(tempcurrentUser);
        clientContext.executeQueryAsync(function () {
            prf.loggedUser = tempcurrentUser.get_id();
            var userAcc = tempcurrentUser.get_loginName();                
        }, queryFailure);
    }
    catch (err) {
        queryFailure();
    }
}

function queryFailure() {
    alert('Error while accessing Active Directory');
}

In above code when I am trying to access SP.ClientContext.get_current(), I am getting error stating SP.ClientContext is undefined.

I am new to SharePoint online, this question may be sound easy but I am open to learn.

Note: Above code is working fine in SharePoint 2013.

salah9
  • 502
  • 1
  • 10
  • 21

3 Answers3

1

To get user information in SharePoint online, there is no need to write code. You can use existing _spPageContextInfo provided by Microsoft.

Code with output:

enter image description here

0

Instead of using SP.SOD.executeFunc try using

‘executeOrDelayUntilScriptLoaded’

https://learn.microsoft.com/en-us/previous-versions/office/developer/sharepoint-2010/ff411788(v%3doffice.14)

S. Walker
  • 2,129
  • 12
  • 30
0

In SharePoint Online, I suggest you use REST API and jQuery Ajax to achieve it.

<script src="https://code.jquery.com/jquery-1.12.4.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function(){
    $.ajax({
        url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/CurrentUser",
        method: "GET",
        headers: { "Accept": "application/json; odata=verbose"},
        async:false,
        success: function (data) {
            var userId=data.d.Id;
            var loginName=data.d.LoginName;
            alert("UserId:"+userId+"  LoginName:"+loginName);
        },
        error: function (err) {
            console.log(err);
        }
    });
});
</script>

If you want to get current user profile information, we can use the REST API below.

https://siteurl/_api/SP.UserProfiles.PeopleManager/GetMyProperties

Reference: SharePoint 2013: Get UserProfile Properties with REST API

LZ_MSFT
  • 4,079
  • 1
  • 8
  • 9