1

When use this script it’s display my user it’s OK but after share it with my colleague it is not updating to the current user it’s shows my display name

<div id="displayName"></div>  

<script type="text/javascript">
var clientContext = new SP.ClientContext(_spPageContextInfo.webServerRelativeUrl);
var user = clientContext.get_web().get_currentUser();
clientContext.load(user);

clientContext.executeQueryAsync(onUserNameSuccess, onUserNameFail);
function onUserNameSuccess() {
    document.getElementById("displayName").innerText = "Welcome, " + user.get_title();
    //To display last name first and for cases where full name consists of only two words.
    //var userToken = user.get_title().split(' ');
    //document.getElementById("displayName").innerText = "Welcome, " + userToken[1] + " " + userToken[0];

}

function onUserNameFail(args) {
    document.getElementById("displayName").innerText = 'Error:' + args.get_message();
}
//recommended to use ExecuteOrDelayUntilScriptLoaded on sp.js
</script>
0

Instead of JSOM, you can use below REST API code which is more robust:

<script type="text/javascript">

var loginName = "";
var userid = _spPageContextInfo.userId;
GetCurrentUser();

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.Title;
    alert("Hello " + loginName);

    // to set the "hello username" into the page
    document.getElementById("id").innerHTML = "Hello " + loginName;
    }

function onError(error) {
  alert(error);
  }

</script>

Source:

Get current logged in user and display it on the Site as “Hello (Username)”

Or You can use the below JSOM function:

function GetCurrentUsername()
{
var ctxt = new SP.ClientContext.get_current();
this.website = ctxt.get_web();
this.currentUser = website.get_currentUser();
ctxt.load(currentUser);
ctxt.executeQueryAsync(Function.createDelegate(this, this.onSucceess), Function.createDelegate(this, this.onFail));
}



function onSucceess(sender, args)
 {
 alert(currentUser.get_loginName());
 }



function onFail(sender, args)
{
alert('request failed ' + args.get_message() + '\n'+ args.get_stackTrace());
}

Source:

How to get the login name of the current user using JavaScript?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.