Sharepoint - How to get current user with javascript?
This code worked:
function CallClientOM()
{
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());
}
If you only want to count items created by a current user, you don't need the whole current user object. Everything you need is the the id of the current user:
var userId = _spPageContextInfo.userId;
Then you can use this id for creating the caml queries. This id is already on the page, so you avoid an asynchronous server call. Take inspirations from other similar questions and answers on sharepoint.stackexchange: Javascript get guid from Sharepoint and can i get the last ID from document library?
Have you tried jQuery SPServices api. There is a direct method given in the library. I used it.
http://spservices.codeplex.com/wikipage?title=$().SPServices.SPGetCurrentUser
Hope this helps you!
Also, I think you should load the web first and then you can get the current user.