Take the 2-minute tour ×
SharePoint Stack Exchange is a question and answer site for SharePoint enthusiasts. It's 100% free, no registration required.

This question already has an answer here:

I am trying to store the username return by the variable username using the code below, but it seems nothing is returned (Username:undefined pops up), may somebody advise how to make it works?

var username;
siteUrl = 'xxx/xxx';

function getLogonUser() {
    var clientContext = new SP.ClientContext(siteUrl);
    this.website = clientContext.get_web();
    this.currentUser = website.get_currentUser();
    clientContext.load(currentUser);
    clientContext.executeQueryAsync(Function.createDelegate(this, this.userQuerySucceeded), Function.createDelegate(this, this.userQueryFailed));

}

function userQuerySucceeded(sender, args) {
    this.username = currentUser.get_loginName();
}

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


function showName(){
    getLogonUser();
    alert('Username:' + this.username);
}
share|improve this question

marked as duplicate by Benny Skogberg, RJ Cuthbertson, PirateEric, Robert Lindgren, SPArchaeologist Sep 11 '13 at 13:57

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

1 Answer 1

up vote 4 down vote accepted

All calls to SharePoint in the JavaScript Object Model are Asynchronous. This means that you have to make use of callback functions to get values back successfully. In your code, you have used the userQuerySucceeded callback function to fire when your query succeeds. Now to read the login name, you will have to do it inside the callback function. Try this code:

var username;
siteUrl = 'xxx/xxx';

function getLogonUser() {
    var clientContext = new SP.ClientContext(siteUrl);
    this.website = clientContext.get_web();
    this.currentUser = website.get_currentUser();
    clientContext.load(currentUser);
    clientContext.executeQueryAsync(Function.createDelegate(this, this.userQuerySucceeded), Function.createDelegate(this, this.userQueryFailed));

}

function userQuerySucceeded(sender, args) {
    this.username = currentUser.get_loginName();
    alert('Username:' + this.username);
}

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


function showName(){
    getLogonUser();

}
share|improve this answer
    
But can this.username be used in another function? –  user1758952 Aug 19 '13 at 6:42
1  
Yes. But make sure you call that function inside userQuerySucceeded –  Vardhaman Deshpande Aug 19 '13 at 7:00

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