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);
});
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