0

I have the following JS, my alert statement returns undefined. However if I place it within the function it returns the correct value. How can I pass the variable accName outside of the function so that I can use it elsewhere?

Thanks in advance.

<script src="/codelibrary/jquery.SPServices-2014.02.min.js" type="text/javascript"></script>
<script src="/codelibrary/jquery-1.11.3.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
    var accName;
    GetUser();
    alert(accName);
});

function GetUser(accName) {
    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) {
    displayName = data.d.Title;
    loginName = data.d.LoginName;
    accName1 = loginName.split('|')[2];
    accName = accName1;
    return accName;
}

function onError(error) {
    alert("error");
}
</script>
Tushar
  • 85,780
  • 21
  • 159
  • 179
  • 1
    AJAX is *asynchronous*. Your `alert(accName);` will run *before* the AJAX is done. AJAX runs, then rest of your code runs, and the callback is ran at some point in the future. – gen_Eric Jun 18 '15 at 14:19
  • 1
    Aside from the async thing, avoid using globals. Instead, have `GetUser` accept a callback or return a promise, so the caller can decide what to do with the user information. – T.J. Crowder Jun 18 '15 at 14:21
  • Also adding the “[canonical question](http://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron)”. – Sebastian Simon Jun 18 '15 at 14:22

0 Answers0