5

My goal is to get the login name and picture for the current user. I am using SharePoint 2013 Foundation. I tried three method and non of then worked correctly:

  1. This is with jQuery SPServices:

    function getCurrentUserInfo() {
        var thisUsersValues = $().SPServices.SPGetCurrentUser({
            fieldNames: ["ID", "Name", "Picture"],
            debug: false
        });
    
        var name = thisUsersValues["Name"];
    
        var ID = thisUsersValues["ID"];
    
        var SIPAddress = thisUsersValues["Picture"];
    
    }
    

But I am getting this error:

SCRIPT438: Object doesn't support property or method 'replace'

File: jquery.SPServices-2014.01.js, Line: 2414, Column: 17

  1. REST API method:

    function getinfo(loginName) {
        var theData = {
            "propertiesForUser": {
                "__metadata": { "type": "SP.UserProfiles.UserProfilePropertiesForUser" },
                "accountName": loginName,
                "propertyNames": ["PreferredName", "PictureURL"]
            }
        };
    
        var requestHeaders = {
            "Accept": "application/json;odata=verbose",
            "X-RequestDigest": jQuery("#__REQUESTDIGEST").val()
        };
    
        jQuery.ajax({
            url: _spPageContextInfo.webAbsoluteUrl + "/_api/SP.UserProfiles.PeopleManager/GetUserProfilePropertiesFor",
            type: "POST",
            data: JSON.stringify(theData),
            contentType: "application/json;odata=verbose",
            headers: requestHeaders,
            success: function (data) {
                document.getElementById("profilelink").href = userProfileProperties[1];;
                document.getElementById("username").innerHTML = userProfileProperties[0];
                if (userProfileProperties[1] !== null) {
                    document.getElementById("Userprofileimage").src = userProfileProperties[1];
                }
            },
            error: function (jqxr, errorCode, errorThrown) {
                console.log(jqxr.responseText);
            }
        });
    }
    

Error:

"{\"error\":{\"code\":\"-1, Microsoft.SharePoint.Client.InvalidClientQueryException\",\"message\":{\"lang\":\"en-US\",\"value\":\"The method GetUserProfilePropertiesFor cannot be invoked as its parameter propertiesForUser is not supported.\"},\"innererror\": {\"message\":\"The method GetUserProfilePropertiesFor cannot be invoked as its parameter propertiesForUser is not supported.\" ,\"type\":\"Microsoft.SharePoint.Client.InvalidClientQueryException\",\"stacktrace\":\"

  1. With CSOM:

    //SP.SOD.executeOrDelayUntilScriptLoaded(getUserProperties, 'SP.UserProfiles.js');
    function getUserProperties(targetUser) {
    
        // get the target users domain name and account name.
        var tUser = targetUser.substring(7);
        // Get the current client context.
        var clientContext = new SP.ClientContext.get_current();
        //Get PeopleManager Instance
        var peopleManager = new SP.UserProfiles.PeopleManager(clientContext);
        // Get the properties to retrieve
        var profilePropertyNames = ["PreferredName", "PictureURL"];
        var userProfilePropertiesForUser = new SP.UserProfiles.UserProfilePropertiesForUser(
            clientContext,
            tUser,
            profilePropertyNames);
        // Get user profile properties for the target user
        userProfileProperties = peopleManager.getUserProfilePropertiesFor(userProfilePropertiesForUser);
        // Load the UserProfilePropertiesForUser object.
        clientContext.load(userProfilePropertiesForUser);
        //Execute the Query
        clientContext.executeQueryAsync(onRequestSuccess, onRequestFail);
    }
    

I really don't understand where the issue is. Does anyone have an idea?

13

SP Foundation does not include the User Profile Service, as @Aveenav noted. Therefore you probably do not have access to the REST endpoints for that service. Instead you will have to use the user information list to get this information. This will require two requets: one to get the current user's id, the second to get the user's info that you want.

First request:

/_api/Web/CurrentUser?$select=Id

Second request (Id will be the Id returned in first request):

/_api/Web/SiteUserInfoList/Items(Id)?$select=Name,Picture

My results: REST results for second request

Edit

Since you're doing this from an app, you might have to make some changes (not sure if the app web will contain the User Info List). Change the urls to the following:

appwebUrl + "/_api/SP.AppContextSite(@target)/Web/CurrentUser?$select=Id&@target='" + encodeURIComponent(hostUrl) + "'"

appwebUrl + "/_api/SP.AppContextSite(@target)/Web/SiteUserInfoList/Items(Id)?$select=Name,Picture&@target='" + encodeURIComponent(hostUrl) + "'"

App will require appropriate permissions.

  • thank you all , i tried :/_api/Web/SiteUserInfoList/Items(Id)?$select=Name,Picture in the navigator and it works fine , but whenuse the ajax function i got this error : SCRIPT7002: XMLHttpRequest: Network Error 0x80070005, Access is denied. – Imen Turki Dec 12 '14 at 9:27
  • Where are you executing the code from? An app or a SharePoint page? – wjervis Dec 12 '14 at 13:10
  • I execute the code from an app – Imen Turki Dec 12 '14 at 14:35
5

1) Get all properties of current user:

http://siteurl/_api/SP.UserProfiles.PeopleManager/GetMyProperties

2) Get single property of current user:

http://siteurl/_api/SP.UserProfiles.PeopleManager/GetMyProperties/PictureUrl

OR

http://siteurl/_api/SP.UserProfiles.PeopleManager/GetMyProperties?$select=PictureUrl

3) Get Multiple Properties for the current user:

http://siteurl/_api/SP.UserProfiles.PeopleManager/GetMyProperties?$select=PictureUrl,AccountName

4) Get all properties of Specific User:

For Office 365/SharePoint Online:

http://siteurl/_api/SP.UserProfiles.PeopleManager/GetPropertiesFor(accountName=@v)?@v='i:0%23.f|membership|vardhaman@siteurl.onmicrosoft.com'

For SharePoint 2013 On-Premise:

http://siteurl/_api/SP.UserProfiles.PeopleManager/GetPropertiesFor(accountName=@v)?@v='domain\username'

5) Get Specific UserProfile Property of Specific User:

For Office 365/SharePoint Online: http://siteurl/_api/SP.UserProfiles.PeopleManager/GetUserProfilePropertyFor(accountName=@v,propertyName='LastName')?@v='i:0%23.f|membership|vardhaman@siteurl.onmicrosoft.com'

For SharePoint 2013 On-Premise:

http://siteurl/_api/SP.UserProfiles.PeopleManager/GetUserProfilePropertyFor(accountName=@v,propertyName='LastName')?@v='domain\username'

http://www.vrdmn.com/2013/07/sharepoint-2013-get-userprofile.html

NOTE: I had issues with getting the specific property for a user on #5. This worked fine though:

http://siteUrl/_api/SP.UserProfiles.PeopleManager/GetPropertiesFor(accountName=@v)?@v='cnmain\ben-phillips'&$select=DisplayName,AccountName,PictureUrl
  • <m:message xml:lang="en-US"> The security validation for this page is invalid and might be corrupted. Please use your web browser's Back button to try your operation again. </m:message> i go this error – Imen Turki Dec 11 '14 at 17:05
  • Try accessing the urls in your browser first when testing REST calls. – MickB Dec 11 '14 at 17:12
  • yes i test it all using rest client for mozilla : and i alyaws having error : at Microsoft.Office.Server.UserProfiles.PeopleManager.GetMyProperties() at Microsoft.Office.Server.UserProfiles.PeopleManagerServerStub.InvokeMethod(Object target, String methodName, ClientValueCollection xmlargs, ProxyContext proxyContext, Boolean& isVoid) at Microsoft.SharePoint.Client.ServerStub.InvokeMethodWithMonitoredScope(Object target, String ... – Imen Turki Dec 11 '14 at 17:32
  • http://siteurl/_api/SP.UserProfiles.PeopleManager and http://siteurl/_api/SP.UserProfiles.PeopleManager\GetMyProperties return an error in IE? – MickB Dec 11 '14 at 17:53
  • yes mick , it return an error in IE , I use IE11, – Imen Turki Dec 12 '14 at 14:36
1

For REST api, you could use 'GetMyProperties'. Use '$select' to retrieve only specific properties. the ajax method should be 'GET'. Here's a working example:

$.ajax({
    url: _spPageContextInfo.webServerRelativeUrl +
         "_api/SP.UserProfiles.PeopleManager/GetMyProperties?$select=DisplayName, PictureUrl",
    method: "GET",
    headers: {
        "accept": "application/json;odata=verbose"
    },
    success: function (data) {
        var result = data.d;
        var displayName = result.DisplayName;
        window.console && console.log(displayName);

        var picUrl = result.PictureUrl;
        window.console && console.log(picUrl);

    },
    error: function (err) {
        alert(JSON.stringify(err));
    }
});
  • i tried it and this is the error: responseText "Common Language Runtime detected an invalid program.\",\"type\":\"System.InvalidProgramException\",\"stacktrace\":\" at Microsoft.Office.Server.UserProfiles.PeopleManager.GetMyProperties()\\r\\n at Microsoft.Office.Server.UserProfiles.PeopleManagerServerStub.InvokeMethod(Object target, String methodName, – Imen Turki Dec 11 '14 at 17:29
  • 2
    does SP 2013 Foundation has user profiles? – Aveenav Dec 11 '14 at 18:20

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.