Sunday, 26 July 2015

Get current user using javascript - SharePoint client object model

Hi All,

  In this post we will see about, getting the loggedin Username using Javascript only.
In Client object model , to get the value of the loggedin User, mostly everyone will go for $().SPServices.SPGetCurrentUser. SP Services ibrary has tons of uses and is very easier.
But we can do this without referencing a third party library, if your requirement is like so.

Below given is the code for it.

function getCurrentUser()
{
var context = new SP.ClientContext.get_current();
this.website = context.get_web();
this.currentUser = website.get_currentUser();
context.load(currentUser);
context.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));
}



function onQuerySucceeded(sender, args)
 {
 alert(currentUser.get_loginName());
 }



function onQueryFailed(sender, args)
{
alert('request failed ' + args.get_message() + '\n'+ args.get_stackTrace());
}

Hope this helps somewhere. Happy coding..

No comments:

Post a Comment