Can you say why this code doesn't work for me? SharePoint 2010. I have no ideas any more about how to set this value to global object :(

ExecuteOrDelayUntilScriptLoaded(getWebUserData, "sp.js");
var context = null;
var web = null;
var currentUser = null;
var currentUserData = {
"userLogin": "templogin"

function getWebUserData() {
    context = new SP.ClientContext.get_current();
    web = context.get_web();
    currentUser = web.get_currentUser();
    context.executeQueryAsync(Function.createDelegate(this, this.onSuccessMethod), 
         Function.createDelegate(this, this.onFailureMethod));

function onSuccessMethod(sender, args) {
    var userObject = web.get_currentUser();
    alert('User name:' + userObject.get_title() + '\n Login Name:' + 
    // export loginName value into global object
    currentUserData.userLogin = userObject.get_loginName();

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

// output (alert) value from global obj properties.
// it doesn's work.
alert("Once more time: \n Current User Login: " + currentUserData.userLogin);
  • Are you getting null in the alert box? I think its because the value is not initialized. – Amal Hashim Mar 16 '15 at 12:39
  • declare the variables before calling ExecuteOrDelayUntilScriptLoaded(getWebUserData, "sp.js"); – Eric Alexander Mar 16 '15 at 12:43
  • Hello! I have a "templogin" in alert message – SPNick Mar 16 '15 at 12:43

This is happening because of the asynchronous behaviour of JavaScript Client Object model. The statement alert("Once more time: \n Current User Login: " + currentUserData.userLogin); is executed immediately after ExecuteOrDelayUntilScriptLoaded(getWebUserData, "sp.js"); It does not wait for success handler to finish. If you put alert after currentUserData.userLogin = userObject.get_loginName(); it should work. However, if your need is to use it outside, then you may use JavaScript callbacks or JQuery Defrreds/Promises. See this for more information: http://www.sharepointnadeem.com/2014/10/sharepoint-using-deferredspromises-or.html

  • Thank you, Nadeem! Very useful post! I'll try to play with callbacks today. – SPNick Mar 16 '15 at 13:27

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.