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 =(

Samuel_
  • 177
  • 3
  • 16
  • 1
    Please refer to the following post [http://sharepoint.stackexchange.com/questions/44499/how-to-get-current-user-with-javascript][1] – Mokhtar Bepari Jul 21 '14 at 07:49
  • This code doesn't work `web.get_currentUser();`. I have already the same result `Undefined` ... – Samuel_ Jul 21 '14 at 08: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. – John-M Jul 21 '14 at 18:06

3 Answers3

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');
Vadim Gremyachev
  • 57,952
  • 20
  • 129
  • 193
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.

Community
  • 1
  • 1
  • 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_ Jul 21 '14 at 08:39
  • @Samuel_ you should be able to use a standard script tag in a content editor -- -- 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 – John-M Jul 21 '14 at 18:18
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();