I am new to this, and I am just trying to understand how to use some of the javascript I have learned in different ways. This may be a question of context, but an examples or explanation is always greatly appreciated as I am trying to learn.
I have a CEWP referencing a text file in a document library that contains the following script. This works for alerts, but I am trying to use a document.write to display the results within the CEWP.
<script type="text/javascript">
_spBodyOnLoadFunctionNames.push("loadScript");
function loadScript()
{
ExecuteOrDelayUntilScriptLoaded(findUser, 'sp.js');
}
function findUser()
{
cxt = new SP.ClientContext.get_current();
web = cxt.get_web();
this._currentUser = web.get_currentUser();
cxt.load(this._currentUser);
cxt.executeQueryAsync(Function.createDelegate(this, this.onSuccessMethod),
Function.createDelegate(this, this.onFailureMethod));
}
function onSuccessMethod(sender, args)
{
alert('Welcome ' + this._currentUser.get_title());
}
function onFaiureMethod(sender, args)
{
alert('request failed ' + args.get_message() + '\n' + args.get_stackTrace());
}
</script>
So the above works (though probably wouldn't use it since it displays welcome everytime the page loads), but I am still learning and used it to help figure out the syntax/etc and I need something like a document.write to write the value back into the CEWP. I can't seem to figure out how to use that and call any of the functions and get a value returned, and tried a bunch of things that probably don't make sense (I tried adding document.write inside the function and I got the value back, but none of the rest of the page). So I really looking for some help understanding javascript and using SP.ClientContext in this way.
EDIT: Basically how can I set a value in a variable within the onSuccessMethod and return that back out of the functions to a global var? This would allow me to accomplish exactly what I am trying to do. If I simply try to create a global list this
var myOutput = loadScript();
and set this inside onSuccessMethod:
myOutput = "Welcome " + this._currentUser.get_title());
return myOutput;
...I can set an alert in the middle of the above and see that myOutput holds the message value perfectly, but myOuput outside of these functions still reflects undefined. I have tried initializing it first, passing/accepting var as param through scriptLoader and findUser, and a bunch of other simple things, but I fear there is something about this I am simply misunderstanding.
Any/all helps is greatly appreciated as always!