0

I'm having an issue with this code for pulling usernames from sharepoint.

The function GetuserName() works fine if i change return loginName to alert(loginName); and then i just call the function.

but i'm trying to pull back the value and add it to the arrVal array.

however it's not working, while testing with alerts if I alert(GetUserName()); I get an undefined alertbox. i'm guessing i'm calling the return back wrong but i'm not sure.

Any help would be really useful

(document).on('click', '.genbutt', function() {
    var $row = jQuery(this).closest('tr');
    var $columns = $row.find('td');

    $columns.addClass('row-highlight');
    var values = "";
    var arrVal = [];
    jQuery.each($columns, function(i, item) {
        values = values + item.innerHTML + " ";
        arrVal = values.split(" ");


    });

    alert(GetUserName());

});

function GetUserName() {
    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: onSuccess,
        error: onError
    });

    function onSuccess(data, request) {
        var loginName = data.d.Title;
        var emailName = _spPageContextInfo.userLoginName;
        return loginName;

    }

    function onError(error) {
        alert("error");
    }
}
adam Wadsworth
  • 774
  • 1
  • 8
  • 26
  • You need to add callback for GetUserName. The alert gets executed before the ajax returned the result. – RahulB Sep 03 '18 at 11:21

2 Answers2

0

The AJAX call is asynchronous, that's why the alert doesn't immediately receive a value back and therefore it displays undefined. You could use a callback:

GetUserName((val) => {alert(val)})

And change your GetUserName to

GetUserName(cb) {
   ... cb(loginName) ... //Instead of return
}
Stefan Blamberg
  • 816
  • 9
  • 24
  • sorry could you flesh this out a bit more for me my ajax call on success calls another function onSuccess which is supposted to then return the login Name where in which function would i be putting the cb(loginName)? – adam Wadsworth Sep 03 '18 at 11:42
  • See this example, it uses a timeout instead of a ajax call but its basically the same, hope that helps function GetUserName(cb) { setTimeout(onSuccess, 1000); function onSuccess() { cb("Hi") } } GetUserName((res) => {alert(res);}) – Stefan Blamberg Sep 03 '18 at 13:30
  • 1
    Thank you but i now understand your original answer and with a bit of looking at the duplicate question responces i managed to make a callback work which i asume is what you were trying to tell me to do. – adam Wadsworth Sep 03 '18 at 13:48
0

Your problem, is that ajax is async, and getUserName() has no return statement. Your return statement is for function onSuccess.

Adrian Godoy
  • 165
  • 11