1

Hy

I need to find the current user from my SharePoint. I have tried many things :

  • SP.Utilities.PrincipalInfo.get_loginName()
  • _spPageContextInfo.userId
  • ...

At all times, I have the same result Undefined =(

3
  • 1
    Please refer to the following post [sharepoint.stackexchange.com/questions/44499/… Commented Jul 21, 2014 at 7:49
  • This code doesn't work web.get_currentUser();. I have already the same result Undefined ... Commented Jul 21, 2014 at 8:41
  • so if you go into chrome on your site, open the dev tools, and type in _spUserId or _spPageContextInfo.userId you get Undefined? If you have values when you do that in the javascript console then Vadim's answer should work -- if you still have Undefined then there is something else wrong with your page that is causing the JS not to execute properly. Commented Jul 21, 2014 at 18:06

3 Answers 3

4

When using CSOM API to retrieve current user object,wrap your code inside SP.SOD.executeOrDelayUntilScriptLoaded method to make sure that the specified code is executed after SharePoint JS library (sp.js) is loaded:

SP.SOD.executeOrDelayUntilScriptLoaded(function(){
   //your code goes here..
}, 'sp.js');

How to retrieve current user object using CSOM API

function getCurrentUser(success,error)
{
    var ctx = SP.ClientContext.get_current();
    var web = ctx.get_web();
    var currentUser = web.get_currentUser();
    ctx.load(currentUser);
    ctx.executeQueryAsync(function(){
        success(currentUser);
    },
    error);
}

Usage

SP.SOD.executeOrDelayUntilScriptLoaded(function(){
  getCurrentUser(
    function(currentUser){
      console.log(currentUser.get_loginName());
    },
    function(sender, args)
    {
      console.log('Request failed ' + args.get_message() + ':'+ args.get_stackTrace());
    }); 
}, 'sp.js');
Sign up to request clarification or add additional context in comments.

Comments

0

The answer is probably here. The only thing i changed is getting LoginName instead of Title:

https://stackoverflow.com/a/21002895/1680288

var userid= _spPageContextInfo.userId;
var requestUri = _spPageContextInfo.webAbsoluteUrl + "/_api/web/getuserbyid(" + userid + ")";
var requestHeaders = { "accept" : "application/json;odata=verbose" };
$.ajax({
    url : requestUri,
    contentType : "application/json;odata=verbose",
    headers : requestHeaders,
    success : onSuccess,
    error : onError
});

function onSuccess(data, request){
    var loginName = data.d.LoginName;
    alert(loginName);
}

function onError(error) {
    alert("error");
}

If you are getting undefined.. Maybe you are not authenticated or did not include some relevant javascript files in your master page.

2 Comments

With this solution, I have this error $ is not defined. I need to make a import of an JQuery script. But I can't import a script.
@Samuel_ you should be able to use a standard script tag in a content editor -- <script type="text/javascript" src="ajax.aspnetcdn.com/ajax/jQuery/…> -- make sure you use https if your site is https... it looks like the mini-markdown formatting is messing up the tag... but point being you can add it just like you were writing it on the page source
0

Without jquery:

var userid= _spPageContextInfo.userId;
var requestUri = _spPageContextInfo.webAbsoluteUrl + "/_api/web/getuserbyid(" + userid + ")";


function createXMLHttp() {
  //If XMLHttpRequest is available then using it
  if (typeof XMLHttpRequest !== undefined) {
    return new XMLHttpRequest;
  //if window.ActiveXObject is available than the user is using IE...so we have to create the newest version XMLHttp object
  } else if (window.ActiveXObject) {
    var ieXMLHttpVersions = ['MSXML2.XMLHttp.5.0', 'MSXML2.XMLHttp.4.0', 'MSXML2.XMLHttp.3.0', 'MSXML2.XMLHttp', 'Microsoft.XMLHttp'],
        xmlHttp;
    //In this array we are starting from the first element (newest version) and trying to create it. If there is an
    //exception thrown we are handling it (and doing nothing ^^)
    for (var i = 0; i < ieXMLHttpVersions.length; i++) {
      try {
        xmlHttp = new ActiveXObject(ieXMLHttpVersions[i]);
        return xmlHttp;
      } catch (e) {
      }
    }
  }
}   

function getData() {
  var xmlHttp = createXMLHttp();
  xmlHttp.open('get', requestUri , true);
  xmlHttp.setRequestHeader("Content-Type", "application/json;odata=verbose");     
  xmlHttp.setRequestHeader("accept", "application/json;odata=verbose");   
  xmlHttp.send(null);
  xmlHttp.onreadystatechange = function() {
    if (xmlHttp.readyState === 4) {
      if (xmlHttp.status === 200) {
        var data = JSON.parse(xmlHttp.responseText);
        var loginName = data.d.LoginName;
        alert(loginName);

      } else {
      }
    } else {
      //still processing
    }
  };
}   

getData();

1 Comment

same problem as your other answer, will not work on 2010

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.