1

Have a question about a user's unqiue id in SP2013: namely, how to get the current user's id via a Javascript REST call.

I have some lists that have a user lookup and the ID stored in this lookup is the same as in _spPageContextInfo.userId. However, when I do a REST call to https://[mysite]/_api/web/currentUser I get a different ID.

How do I make a REST call that would get me the same value as _spPageContextInfo.userId ?

Example

_spPageContextInfo.userId === 540 // same value as in List columns

var g = $.ajax({
  url: "https://[mysite]/_api/web/currentUser",
  headers: {
    "Accept": "application/json; odata=verbose"
  }
});

p.responseJSON.d.Id === 639  // this is different though 

// why is this?
_spPageContextInfo.userId !== p.responseJSON.d.Id
  • 1
    is [mysite] your current web or different web or site collection? – Aveenav Sep 15 '16 at 18:22
4

If you're using different web (or site) the user Id(s) will differ. Since _api is a virtual folder it can be called from any web. In your case, use the current web. See the snippet below:

window.console && console.info('spPageContextInfo user Id: ' + _spPageContextInfo.userId);

function getCurrentWebUrl() {
    var webUrl = _spPageContextInfo.webServerRelativeUrl;
    return webUrl.endsWith("/") ? webUrl : webUrl + "/";
}

var p = $.ajax({
    url: getCurrentWebUrl() + "_api/web/currentUser",
    headers: {
        "Accept": "application/json; odata=verbose"
    }
});

p.done(function (data) {
    window.console && console.info('From ajax response: user Id ' + data.d.Id);
});
| improve this answer | |
  • Sorry for the super long delay but I got pulled into another project. Yes! Adding the sub-site to the URL fixed the issue. Thanks so much and glad it was so simple! – thornomad Oct 20 '16 at 17:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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