16

I have a list . I want select items of list with a special quary.(get items that created with current user). Then get count of items.

I use this code for get current user :

function Initialize()
{
    context = new SP.ClientContext.get_current();
    web = context.get_web();
   var currentUser = web.get_currentUser();
   alert(currentUser);
    currentUser.retrieve();
    context.load(web);
    context.executeQueryAsync(Function.createDelegate(this, this.onSuccessMethod), 
         Function.createDelegate(this, this.onFailureMethod));
}

function onSuccessMethod(sender, args) {
    var userObject = web.get_currentUser();
    alert('User name:' + userObject.get_title() + '\n Login Name:' + 
             userObject.get_loginName());
}
function onQueryFailed(sender, args) {
    alert('request failed ' + args.get_message() + '\n' + args.get_stackTrace());
}

But don't get current user.

and use this code for get items of list.

 function Initialize()
{
    clientContext = new SP.ClientContext.get_current();
    web = clientContext.get_web();

    var list = web.get_lists().getByTitle("Sends");
    var camlQuery = new SP.CamlQuery();
    var q = "<Where><Eq><FieldRef Name='CreatedUser' /><Value Type='User'>CurrentUser</Value></Eq></Where>";
    camlQuery.set_viewXml(q);
    this.listItems = list.getItems(camlQuery);
     clientContext.load(listItems, 'Include(ID)');

    clientContext.executeQueryAsync(Function.createDelegate(this, this.onListItemsLoadSuccess), 
    Function.createDelegate(this, this.onQueryFailed));
}
function onListItemsLoadSuccess(sender, args) {
    var count = 0;

     count = this.listItems.get_count();

           }

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

5 Answers 5

18

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());
}
3
  • This worked for me, too (SP Enterprise 2010). Thanks!
    – bgmCoder
    Commented Dec 7, 2012 at 4:04
  • Can you tell me how to get the other properties like any custom defined?
    – Strider
    Commented Jul 24, 2014 at 8:10
  • do not forget to call the defined function _spBodyOnLoadFunctionNames.push("CallClientOM")
    – Iman
    Commented Nov 26, 2014 at 13:05
12

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?

0
10

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.

1
  • Using SPServices for this specific task is such a bad idea: "SPGetCurrentUser function does an AJAX call to grab /_layouts/userdisp.aspx?Force=True and "scrapes" the values from the page based on the internal field name (aka StaticName)"
    – Jussi Palo
    Commented Oct 9, 2017 at 8:27
3

Following code is working for me,

    var context = null;
    var web = null;
    var currentUser = null;
    function getWebUserData() {
        context = new SP.ClientContext.get_current();
        web = context.get_web();
        currentUser = web.get_currentUser();
        currentUser.retrieve();
        context.load(web);
        context.executeQueryAsync(Function.createDelegate(this, this.onSuccessMethod), Function.createDelegate(this, this.onFailureMethod));
    }
    function onSuccessMethod(sender, args) {
        var userObject = web.get_currentUser();
        alert('User name:' + userObject.get_title() + '\n Login Name:' + userObject.get_loginName());
    }
    function onFailureMethod(sender, args) {
        alert('request failed ' + args.get_message() + '\n' + args.get_stackTrace());
    }
    ExecuteOrDelayUntilScriptLoaded(getWebUserData, "sp.js");

try this may be helpful for you :)

3
  • I use this code but don't work for me .
    – ar.gorgin
    Commented Aug 30, 2012 at 5:52
  • what is the error? can you use ExecuteOrDelayUntilScriptLoaded(getWebUserData, "sp.js")? Commented Aug 30, 2012 at 5:53
  • Yes, i use. It is run but don't return current user.
    – ar.gorgin
    Commented Aug 30, 2012 at 5:59
2

This runs completely independent of SharePoint's ridiculous SP.js

function getCurrentUser(callback){
    var user = {};
    var query = '<Query><Where><Eq><FieldRef Name="ID" /><Value Type="Counter"><UserID /></Value></Eq></Where></Query>';
    var viewFields = '<ViewFields><FieldRef Name="ID" /><FieldRef Name="Name" /><FieldRef Name="EMail" /><FieldRef Name="Department" /><FieldRef Name="JobTitle" /><FieldRef Name="UserName" /><FieldRef Name="Office" /></ViewFields>';

    getListItems('', 'User Information List', viewFields, query, function (xmlDoc, status, jqXhr) {

    $(xmlDoc).find('*').filter(function () {
        return this.nodeName == 'z:row';

    }).each(function (i, node) {
        user.id = parseInt($(node).attr('ows_ID'));
        user.title = $(node).attr('ows_Title');
        user.login = $(node).attr('ows_Name');
        user.email = $(node).attr('ows_EMail');
        user.jobtitle = $(node).attr('ows_JobTitle');
        user.department = $(node).attr('ows_Department');
        user.account = user.id + ';#' + user.title;
        user.groups = [];
    });

    callback(user);
    }); 
}

function getListItems(siteUrl, listName, viewFields, query, callback, rowLimit) {
    siteUrl = siteUrl == '' ? '/' : siteUrl;
    rowLimit = rowLimit || 25;

    var packet = '<?xml version="1.0" encoding="utf-8"?>' +
    '<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">' +
    '<soap:Body>' +
    '<GetListItems xmlns="http://schemas.microsoft.com/sharepoint/soap/">' +
    '<listName>' + listName + '</listName>' +
    '<query>' + query + '</query>' +
    '<viewFields>' + viewFields + '</viewFields>' +
    '<rowLimit>' + rowLimit + '</rowLimit>' +
    '</GetListItems>' +
    '</soap:Body>' +
    '</soap:Envelope>';

    var $jqXhr = $.ajax({
        url: siteUrl + '_vti_bin/lists.asmx',
        type: 'POST',
        dataType: 'xml',
        data: packet,
        headers: {
        "SOAPAction": "http://schemas.microsoft.com/sharepoint/soap/GetListItems",
        "Content-Type": "text/xml; charset=utf-8"
        }
    });

    $jqXhr.done(function (xmlDoc, status, error) {
        callback(xmlDoc);
    });

    $jqXhr.fail(function (jqXhr, status, error) {
        callback(null, status + ': ' + error);
    });
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.