0

I am trying to find the ID of the user using _api/web/siteusers in Office 365

I get the below error

User cannot be found

But, when I add user to some people picker field in list item, it starts working

I am using the below code

function GetUserId(userName) {
    //userName format = i:0#.f|membership|alexis.Philip@O365site.com
    var siteUrl = _spPageContextInfo.siteAbsoluteUrl;
    var requesturl = "/_api/web/siteusers(@v)?@v='" + encodeURIComponent(userName) + "'";
    if (userName.indexOf("|") < 0) {
        requesturl = "/_api/web/sitegroups/getbyname('" + encodeURIComponent(userName) + "')?$select=id";
    }
    var call = $.ajax({
        url: siteUrl + requesturl,
        method: "GET",
        headers: { "Accept": "application/json; odata=verbose" }
    });
    return call;
};
2

Try using CSOM:

function getUserId(loginName) {
        var context = new SP.ClientContext.get_current();
        this.user = context.get_web().ensureUser(loginName);
        context.load(this.user);
        context.executeQueryAsync(
        Function.createDelegate(null, ensureUserSuccess),
        Function.createDelegate(null, onFail)
    );
 }
 function ensureUserSuccess() {
        console.log(this.user.get_id());
 }
 function onFail(sender, args) {
        alert('Query failed. Error: ' + args.get_message());
 }

0

The code which at me normally works (NTLM authentication):

function GetUserId(userName) {
        var prefix = "i:0#.w|";
        var siteUrl = _spPageContextInfo.siteAbsoluteUrl;
        var accountName = prefix + userName;
        $.ajax({
            url: siteUrl + "/_api/web/siteusers(@v)?@v='" + 
                encodeURIComponent(accountName) + "'",
            method: "GET",
            headers: { "Accept": "application/json; odata=verbose" },
            success: function (data) {
                alert("Received UserId" + data.d.Id);
                alert(JSON.stringify(data));
            },
            error: function (data) {
                console.log(JSON.stringify(data));
            }
        });
    }
0

Since you are setting your call to a var, try using the .done() function with it. Example below:

var call = $.ajax({
    url: siteUrl + requesturl,
    method: "GET",
    headers: { "Accept": "application/json; odata=verbose" }
});
call.done(function(data) {
    console.dir(data);
    //do stuff
});

Thsi should work for how you are using your REST calls. Good Luck!

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.