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
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? Aug 19 '13 at 6:42
  • 1
    Yes. But make sure you call that function inside userQuerySucceeded Aug 19 '13 at 7:00

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