1

I am creating different forms where I need same functions, so I created separate js file which I call on my each forms.

In below code if alert currentUser from success method then I get the value but If I call currentUser value from my forms in document ready then it will give me "undefined" how can I solve it.

var currentUser;

    $.getScript("/_layouts/15/SP.Runtime.js", function () {
        $.getScript("/_layouts/15/SP.js", execOperation);
    });
function execOperation() {
    // get context and then username
    context = new SP.ClientContext.get_current();
    web = context.get_web();

    getUserName();
}
function getUserName() {
    user = web.get_currentUser();
    context.load(user);
    context.executeQueryAsync(onGetUserNameSuccess, onGetUserNameFail);
}
function onGetUserNameSuccess() {
    currentUser = user.get_loginName();
}
function onGetUserNameFail(sender, args) {
    alert('Failed to get user name. Error:' + args.get_message());
}
function getJSON(url) {
    var requestUri = _spPageContextInfo.webAbsoluteUrl + url;

    $.ajax({
        url: requestUri,
        type: "GET",
        headers: { "ACCEPT": "application/json;odata=verbose" },
        success: function (data) {
            return data.d;
        },
        error: function () {
            alert("Failed to get " + url);
        }
    });
}

This is the way I call from another page

$(document).ready(function () {
        alert(currentUser);
    });
10
  • Where are you calling the getCurrentUser() from? I don't see you calling it. When you debug in developer tools, can you stop on the line: context = new SP.ClientContext.get_current(); and see if SP is loaded? Seems like you're using the SP without it being loaded first. Commented Dec 25, 2015 at 22:30
  • Sorry it was my mistake. I edited my code. But Still it is not working
    – Milind
    Commented Dec 25, 2015 at 22:40
  • did you stop the debugger at the line I told you about? was the SP object undefined at that time? Commented Dec 26, 2015 at 4:49
  • As I told you I am getting value when I calling from success method, but not getting when I call it from another page. That means it is loading SP object
    – Milind
    Commented Dec 26, 2015 at 7:37
  • add console.log( xyz ) statements to all functions and you will see when what is executed. note: your use of global variables inside functions is also something you should fix Commented Dec 26, 2015 at 10:25

1 Answer 1

5

As stated in the comments, you would need to structure your code in a way to get the result of the asynchronous operation, your code should be something like this:

SP.SOD.executeFunc('sp.js', 'SP.ClientContext', getUserName);

var user ;  //declare this as a variable related to your current namespace, only here for demonstration.

function getUserName(){
  var userPromise = retrieveUserCall();
  userPromise    //this line will wait until the server call completes
  .done(function(){
    //do something with user variable
  })
  .fail(function(){
    //do something on fail
  })
}

function retrieveUserCall(){
  var context = new SP.ClientContext();
  var web = context.get_web();
  user = web.get_currentUser();
  context.load(user);
  var dfd = $.Deferred();
  context.executeQueryAsync(function(){
      dfd.resolve();
    },
    function(){
      dfd.reject();
    });
  return dfd;   //dfd will return the result of the server call
}

Note that each call to the server is an asynchornous call, you don't know the result of it right away, and JavaScript will continue executing. So you need to declare a $.Deferred() variable that will store the result of the server call, and you would wait for the execution to complete with .done() for success and .fail() for fail.

8
  • 1
    strictly speaking userPromise will not 'wait' (as in execution stops there) Any code after it (in this case none) will execute. userPromise will 'listen' for an answer, then execute the chained done/fail/always etc. methods. Commented Dec 26, 2015 at 11:52
  • Hi Thanx for the reply with answer as this line is not loading SP.SOD.executeFunc('sp.js', 'SP.ClientContext', getUserName); I am using this $.getScript("/_layouts/15/SP.Runtime.js", function () { $.getScript("/_layouts/15/SP.js", execOperation); }); That is main reason all mess is happening. Any solution for it
    – Milind
    Commented Dec 26, 2015 at 12:43
  • Well, jQuery and sharePoint are not a happy marriage... so use $.getScript only if you know what you are doing.. start learning at: spcaf.com/blog/sharepoint-javascript-context-dev-part-1 Commented Dec 26, 2015 at 12:46
  • @DannyEngelman userPromise code won't get executed until the return dfd is back with either resolve or reject, that's the whole purpose of promises.. Commented Dec 26, 2015 at 12:49
  • any code after userPromise, I was not referring to the promise chain. Commented Dec 26, 2015 at 14:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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