0

This is what the pre-parsed data looks like in the console after querying

http://mysharepointsite/_api/SP.UserProfiles.PeopleManager/GetMyProperties?$select=Department :

enter image description here


I am trying to get the department of the current user and I am having a lot of difficulty.

I am currently at a stage where I am trying to copy this SE question, and I managed to at least get somewhere by running this in PowerShell:

$response = Invoke-WebRequest http://mysharepointsite/_api/SP.UserProfiles.PeopleManager/GetMyProperties?$select=Department -UseDefaultCredentials
$response.Content

Where Content does in fact contain my department (IT), but it is hidden in a load of xml data which I don't need.

I have no idea how to get just the department name using javascript, but this is the code I have at the moment (which is being executed from a content editor web part):

function getUser() {
    var userid = _spPageContextInfo.userId;

    var requestUri = "http://mysharepointsite/_api/SP.UserProfiles.PeopleManager/GetMyProperties";
    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 x = data.department;
        alert(x);
    } 
    function onError(error) {
        alert("Error on retrieving current user.");
    }
}

$(document).ready(function() {
    getUser();
});

Where in this case, I just get an alert which says undefined. Can anyone please help me understand how to parse this incoming data?

  • @GintasK Hi Ginta - I am getting a Invalid character error when this line runs : var parsedData = JSON.parse(data); – Bassie Jun 2 '16 at 15:45
  • There can be 2 things then: the json object is not formed correctly (which I doubt) or the data is parsed already. try using your old code but add console.log(data); and see what your request returns :) – Gintas K Jun 2 '16 at 15:51
  • @GintasK Okay I added an image of what console.log(data); looks like in the console... it is pretty confusing - I have no idea what to do with that! – Bassie Jun 2 '16 at 15:56
1

Try replacing

var x = data.department;
alert(x);

with

var parsedData = JSON.parse(data); 
var x = parsedData.department; 
alert(x);

you can also add

console.log(parsedData);

so you can see inside the returned object in your browser's console :)

UPDATE:

You might need to modify your request url to

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

According to this article

  • @Bassie see my updated answer :) – Gintas K Jun 2 '16 at 16:04

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.