1

new to SP and JS. How do I get the data from my REST call in order to use it in another function? Below is my REST call. If I put a console.log in my success function (instead of returning data) and then call the function it will work and log the data to the console. However, with the code below it is returning undefined.

function GetCurrentUser() {
var userid = _spPageContextInfo.userId;
var requestUri = _spPageContextInfo.webAbsoluteUrl + "/_api/web/getuserbyid(" + userid + ")";

var requestHeaders = { "accept" : "application/json;odata=verbose" };

$.ajax({
  url : requestUri,
  contentType : "application/json;odata=verbose",
  headers : requestHeaders,
  success : function(data){
    return data;
  }
});
}

I tried assigning the function to a variable and then logging the variable but it will only returned undefined. I would like to use the result of this function in another function later. How can I do this? Thanks so much for any and all tips/assistance for a newbie.

var test = GetCurrentUser();
console.log(test);
1

Try below code. It will work for you.

GetCurrentUser().then(GetCurrentUserSuccess, GetCurrentUserFailed);

function GetCurrentUser(){
    var userid = _spPageContextInfo.userId;
    var requestUri = _spPageContextInfo.webAbsoluteUrl + "/_api/web/getuserbyid(" + userid + ")";
    var requestHeaders = { "accept" : "application/json;odata=verbose" };

    return $.ajax({
        url: requestUri,
        type: "GET",
        headers: {
            "accept": "application/json;odata=verbose",
        }
    });
}

function GetCurrentUserSuccess(data){
    //success handler code ('data' is the response we get from server)
    //console.log(data);
    console.log(data.d);
}

function GetCurrentUserFailed(){
    //error handler code goes here
}
3

you can get direct login name using _spPageContextInfo.userLoginName or for display name _spPageContextInfo.userDisplayName.

1

I think that you forgot to indicate type: "GET" your function will be like below :

function GetCurrentUser() {
var userid = _spPageContextInfo.userId;
var requestUri = _spPageContextInfo.webAbsoluteUrl + "/_api/web/getuserbyid(" + userid + ")";

var requestHeaders = { "accept" : "application/json;odata=verbose" };

$.ajax({
  url : requestUri,
  type: "GET",
  contentType : "application/json;odata=verbose",
  headers : requestHeaders,
  success : function(data){
    return data.d.LoginName;
  }
});
}

var accountName = GetCurrentUser();
console.log(accountName);

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.