5

I need to retrieve current user id from login name.

How can that be done? I have used the following code:

var userid=Function??("domain\name");
7

Assuming you are not looking for the current User...I imagine it would be something like this, although I have not tested this nor have I done it before.

    var clientContext = SP.ClientContext.get_current();
    var website = clientContext.get_web();
    currentUser = website.ensureUser("domain\name");
    clientContext.load(website);
    clientContext.load(currentUser);
    clientContext.executeQueryAsync(onRequestSucceeded, onRequestFailed);

    function onRequestSucceeded() {
       var userid =  currentUser.get_id();
    }

    function onRequestFailed(sender, args) {
        //error handling
        alert('Error: ' + args.get_message());
    }

Although it is important to note that ensure user will add the users to the given web if they don't already exist.

  • all correct except the currentUser.UserID should be currentUser.get_id() – svnm Mar 3 '15 at 6:17
3

There's no need to make a request to the server when the userid is already loaded in browser.

You can use:

_spPageContextInfo.userId

available in SharePoint 2013 and Online (wave 16).

  • This one line code is fine but user does not need current login user id – Zakir HC Jul 10 '17 at 6:14
1

To get the userId of a user from the account/login name can be obtained by:

        function GetUserIdFromUserName(userName) {
        /// according to the environment.
        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);
                console.log(JSON.stringify(data));
            },
            error: function (data) {
                console.log(JSON.stringify(data));
            }
        });
    }
0

See for an example on how to get the current user in JavaScript.

Once you have the user, you can use .get_id() to get the record ID for the user.

Your Answer

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