2

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);
}
0

1 Answer 1

5

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();

}
2
  • But can this.username be used in another function? Commented Aug 19, 2013 at 6:42
  • 1
    Yes. But make sure you call that function inside userQuerySucceeded Commented Aug 19, 2013 at 7:00

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.