Wednesday, 24 April 2013

How to get current logged user information using JavaScript

Below is an example using SharePoint’s JavaScript Object Model to retrieve the current logged in username. The SP.Web.currentUser property will return metadata about the user such as the user id, display name,etc..Once you have executed the load and executeQueryAsync methods and the call to SharePoint was sucessful, then inside of the onQuerySucceeded method is where I display the username to the browser using the SP.Principal.get_loginName property. Try it out…you can host and run the code below inside of a content editor web part in SharePoint 2010.


<script type=”text/javascript”>
ExecuteOrDelayUntilScriptLoaded(init,”sp.js”);
var currentUser;
function init(){
this.clientContext = new SP.ClientContext.get_current();
this.oWeb = clientContext.get_web();
currentUser = this.oWeb.get_currentUser();
this.clientContext.load(currentUser);
this.clientContext.executeQueryAsync(Function.createDelegate(this,this.onQuerySucceeded), Function.createDelegate(this,this.onQueryFailed));
}
function onQuerySucceeded() {
document.getElementById(“logUser”).innerHTML = currentUser.get_loginName();
}
function onQueryFailed(sender, args) {
alert(‘Request failed. \nError: ‘ + args.get_message() + ‘\nStackTrace: ‘ + args.get_stackTrace());
}
< /script>
< div>Current Logged User:<label id=”logUser”></label></div>

No comments:

Post a Comment