3

Newbie looking for help here...I have a function to return the current logged in user's name. When I try to access the user's info in a console log as seen below, It is returning undefined. Where am I going wrong? Thanks for you help!

  function createContent(data, listName){
        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){
          alert(data.d.Title);
            return data;
          }
        });
        }

        var arr = data.d.results;
        $(".save").on("click",function(){
                event.preventDefault();
            $("input.title").each(function(){
                var request = $(this).closest("tr").children("td.allItemsTitle").text();
                var title = $(this).val();
                var taskProperties = {
                    '__metadata': { 'type': 'SP.Data.ListItem' },
                    'Rank': title,
                    'RequestName': request
                };

                for(var i = 0;i <= arr.length -1;i++){
                    var item = arr[i];          
                    console.log("request = " + request);
                    console.log("item.RequestName = " + item.RequestName);
//The below console.log is returning "current user = undefined.", instead of "current user = My User Name"
                    console.log("current user = " + GetCurrentUser() + ".");
                    console.log("item.Author[Title] = " + item.Author["Title"]);

                    if(request == item.RequestName && GetCurrentUser() == item.Author["Title"]){
                            console.log('Item has been created successfully');
                    } else {console.log("NO ITEMS CREATED");}
                } 
            });
        });
    }

2 Answers 2

6

A couple of reasons:

  1. AJAX calls are asynchronous. In your console.log statement, you care calling your GetCurrentUser function, which kicks off the call to the REST services, but the console.log is expecting GetCurrentUser to return some value immediately, which it cannot do, because AJAX calls are async and therefore you are still waiting for the response from the server while the console.log is trying to write something.
  2. Your GetCurrentUser function is not going to return the data the way you think it should, because your success callback function is nested inside your GetCurrentUser function. So when your success callback does return data, it's really only returning the data object into the scope of the GetCurrentUser function. You could try something like this:
var restResponse; // defined outside the scope of the GetCurrentUser function

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) {
            alert(data.d.Title);
            restResponse = data; // assign the data to a variable outside the current scope
        }
    });
}

BUT that still won't solve the timing issue. Now, since calling jQuery's ajax function creates a Deferred object, what you could do is have your GetCurrentUser function return the Deferred out to the rest of your code so that you can have the code be waiting in the correct place, like:

function createContent(data, listName) {
    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,
            contentType: "application/json;odata=verbose",
            headers: requestHeaders
        });
    }

    var arr = data.d.results;
    $(".save").on("click", function () {
        event.preventDefault();

        $("input.title").each(function () {
            var request = $(this).closest("tr").children("td.allItemsTitle").text();
            var title = $(this).val();
            var taskProperties = {
                '__metadata': { 'type': 'SP.Data.ListItem' },
                'Rank': title,
                'RequestName': request
            };

            var currentUserRequest = GetCurrentUser();
            // this has created the request to the server, but we still have to wait 
            // for the response from the server to be returned back to the code.
            // also, we want to name the data that is returned in a way that disambiguates 
            // from the "data" object passed into the "createContent" function,
            // because that "data" object is still in scope here.
            currentUserRequest.done(function (userData) {
                for (var i = 0; i <= arr.length - 1; i++) {
                    var item = arr[i];
                    console.log("request = " + request);
                    console.log("item.RequestName = " + item.RequestName);
                    console.log("current user = " + userData.d.Title + ".");
                    console.log("item.Author[Title] = " + item.Author["Title"]);

                    if (request == item.RequestName && userData.d.Title == item.Author["Title"]) {
                        console.log('Item has been created successfully');
                    } else { console.log("NO ITEMS CREATED"); }
                }
            });
        });
    });
}

jQuery "Deferred" documentation

1
  • Thanks so much! That was extremely helpful and solved my problem!
    – loady toad
    Sep 5, 2017 at 19:07
0

Timing issues aside, your ajax success function just returns the entire data response, which would not have matched your item.Author["Title"], unless that item had an entire SharePoint user object as it's author title.

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.