Accessing user profile information in WSS 3.0 with javascript

By Alexander

31.10.2009: Small update for default picture in the example CEWP.

This article describes how to access the “user profile” under WSS 3.0 via javascript. The method used is a query trough the webservice lists.asmx.

I use some code (“interaction.js” and stringBuffer.js”) created by Erucy and published on codeplex.

The jQuery-library is found here. The pictures and the sourcecode refers to jquery-1.3.2.min. If you download another version, be sure to update the script reference in the sourcecode.

As always we begin like this:
Create a document library to hold your scripts (or a folder on the root created in SharePoint Designer). In this example i have made a document library with a relative URL of “/test/English/Javascript” (a subsite named “test” with a subsite named “English” with a document library named “Javascript”):
IMG

You can call this script from any page. In this example i will place it on Default.aspx.

NOTE!
If your site collection resides on a managed path, “wsBaseUrl” in the script must reflect the root of your site collection like this: wsBaseUrl = ‘/myManagedPath/_vti_bin/’;

The sourcecode for the “AccessUserProfileInWSS.js” looks like this:

/* getUserInfo - Returns "user info" data from user list in WSS 3.0 (not MOSS user profile)
 * ---------------------------------------------
 * Created by Alexander Bautz
 * alexander.bautz@gmail.com
 * http://sharepointjavascript.wordpress.com
 * LastMod: 20.09.2009
 * ---------------------------------------------

Define userListGuid (list guid of the user list on your root site) as variable accessible to this script
Refer these scripts:
 interaction.js // Erucy - http://spjslib.codeplex.com
 stringBuffer.js // Erucy - http://spjslib.codeplex.com
 jQuery // http://jQuery.com

Use:
 var ui = getUserInfo(); // If UserId is not specified it assumes it's logged in user (_spUserId)
 alert(ui.Title);
*/

userListGuid = "{680230C5-1095-4247-AA06-9A90CA5539D8}";  // refer userListGuid - do not use this Guid - find your own!

function getUserInfo(UserId){
wsBaseUrl = '/_vti_bin/';
// If your site collection resides on a managed path, "wsBaseUrl" must reflect the root of your site collection like this:
// wsBaseUrl = '/myManagedPath/_vti_bin/';
var uiObj = {};

if(typeof(UserId)=="undefined" || UserId=='')UserId = _spUserId;

var arrOfFields = ['ID', 'Name', 'Title', 'EMail', 'Department', 'JobTitle', 'Notes', 'Picture',
'IsSiteAdmin', 'Created', 'Author', 'Modified', 'Editor', 'SipAddress', 'Deleted'];

var item = getItemById(userListGuid,UserId,arrOfFields);
    if(item != null){
	    for(i=0;i<arrOfFields.length;i++){
	    	if(item[arrOfFields[i]]!=null){
	    		uiObj[arrOfFields[i]] = item[arrOfFields[i]];
	    	}else{
	    		uiObj[arrOfFields[i]] = '';
	    	}
	    }
       	return uiObj;
    }else{
        for(i=0;i<arrOfFields.length;i++){
    		uiObj[arrOfFields[i]] = "User with id " + UserId + " not found.";
    	}
		return uiObj;
	}
}

Save this as a text file and rename to “AccessUserProfileInWSS.js”, then upload to the library as shown above.

This code requires the list guid of the “UserList” in your root site defined as the variable “userListGuid”.

You find the list guid like this:
IMG

IMG

You call the script from a standard CEWP like this:
IMG

Sourcecode for CEWP:

<script type="text/javascript" src="/test/English/Javascript/jquery-1.3.2.min.js"></script>
<script type="text/javascript" src="/test/English/Javascript/interaction.js"></script>
<script type="text/javascript" src="/test/English/Javascript/stringBuffer.js"></script>
<script type="text/javascript" src="/test/English/Javascript/AccessUserProfileInWSS.js"></script>
<script type="text/javascript">

var ui = getUserInfo(); // If UserId is not specified it assumes it's logged in user (_spUserId)
picSrc = '/_layouts/images/person.gif';
if(ui.Picture!=''){
picSrc = ui.Picture.split(',')[0]
}
var str = '';
str += "Accountname: " + ui.Name + "<br>";
str += "Full name: " + ui.Title + "<br>";
str += "E-mail: " + ui.EMail + "<br>";
str += "Department: " + ui.Department + "<br>";
str += "<img alt='' src='" + picSrc + "' />";

document.write(str);
</script>

And you get a result like this:
IMG

I will follow up this article with an article describing how to hide or show form fields based on membership – or not membership – in a SharePoint group.

Alexander

26 Responses to “Accessing user profile information in WSS 3.0 with javascript”

  1. larry Says:

    great work. I have been having an issue, but I do not think it is your script. In the past I was using firebug before I found out about IE Dev Tool. Uues a similar method identifying the user. for some reason I come up as user ID 1, which I always felt to be incorrect. Your script does the same thing and return the message no info for user id 1. Do you know why that might happen? what can be done to fix or change that?

  2. larry Says:

    I did some more digging and still cannot figure out why it can read the user ID 1, but will not return data for user id 1. the first thing that comes to mind is maybe my network firewall, but reading through the scripts, it does not look like it goes outside the firewall. Your script appears to be functioning because it writes the user id in the message. I will continue to look through this. I think this is some great work. whenever I see a request where I think your work would fit I always point them to this blog. keep up the great work

  3. Alexander Says:

    Hi larry,
    The variable _spUserId is supplied by SharePoint, but your page must be attached to a MasterPage for it to be present.

    You can check that your id is correct by looking at your own profile (dropdown on your name in the top right corner – My settings – the id is in the URL-field)

    Check if the variable is present in your page by typing in the URL-field in your browser while in your page: javascript:alert(_spUserId).

    I do believe that it is your ListGuid of your “UserList” that is wrong. please doubleCheck it.

    I will update the script i little bit to replace null-values with a blank string.

    Alexander

  4. larry Says:

    I ran through and everything appears to be correct. My account is userid 1, and your script writes that to the page, just returns not found. I havd come across a similar script a while back that did a similar thing. initially I had the same issue, but I was able to figure out what i did incorrectly, this script http://www.endusersharepoint.com/2009/01/20/jquery-for-everyone-degrading-dynamic-script-loader/ I can write the account Display Name to the page, which appears to doing almost the same thing. I also added this to a different site, updated the listname, still the same results. I will continue to work at this and will let you know what I find

  5. larry Says:

    I am not sure why it can write the _spUserId in the error message, but not write the details to the page. going to have to let it go for now. when I look through the interaction.js file I found references to a few URL. I could not open them in my browser, one was not found and another was error loading. could this be part of the problem?

  6. Alexander Says:

    Hi,
    Did you check the list GUID of your UserList?
    The one supplied in the topmost codeview – line 20 – must be changed to match your List’s GUID.

    Alexander

  7. larry Says:

    Yup checked and double checked

  8. Alexander Says:

    Hi,
    If you have tested with the code supplied unmodified and do not have a picture in your profile – you have to updated the code after i updated it to prevent null-values. Look at the code in line 33-39.

    If this is not the issue – try to insert an alert betveen line 33-34 like this:
    alert(item[arrOfFields[i]]);

    Does it trigger?

    Is your user in a access group with permission (from permission levels) to:

    Use Remote Interfaces – Use SOAP, Web DAV, or SharePoint Designer interfaces to access the Web site.

    And

    Browse User Information – View information about users of the Web site.

    I have not tested with a user without these permissions, but it may influence.

    Alexander

  9. larry Says:

    Updated with new code. I do not have a picute uploaded, and the image place holder has that missing “X”. My user account is a site collection admin. I am also added to the site in a group with full control. your script is working as designed because it writes this to the page:
    User with id 1 not found.
    , and My info is user id 1. I will continue to play with this. Hopefully we can figure this out.

  10. larry Says:

    also I added the alert line, but no alert triggers.

  11. Alexander Says:

    Try this in your CEWP:

    <script type="text/javascript" src="/test/English/Javascript/jquery-1.3.2.min.js"></script>
    <script type="text/javascript" src="/test/English/Javascript/interaction.js"></script>
    <script type="text/javascript" src="/test/English/Javascript/stringBuffer.js"></script>
    <script type="text/javascript" src="/test/English/Javascript/AccessUserProfileInWSS.js"></script>
    <script type="text/javascript">
    alert(getItemById); // Should return the function
    </script>
    

    If this works – try this to alert the loginName:

    <script type="text/javascript" src="/test/English/Javascript/jquery-1.3.2.min.js"></script>
    <script type="text/javascript" src="/test/English/Javascript/interaction.js"></script>
    <script type="text/javascript" src="/test/English/Javascript/stringBuffer.js"></script>
    <script type="text/javascript" src="/test/English/Javascript/AccessUserProfileInWSS.js"></script>
    <script type="text/javascript">
    var ui = getUserInfo(); // If UserId is not specified it assumes it's logged in user (_spUserId)
    alert("testing..."); // Just to see that the alert is working
    alert(ui.Name); // LoginName
    </script>
    

    Alexander

  12. Alexander Says:

    Larry,

    Is your system WSS 3.0 or MOSS 2007?

    Alexander

  13. larry Says:

    wss 3.0, I have not tried the changes yet. I will report back as soon as I get a chance.

    thanks for all your support.

  14. larry Says:

    I put the alerts in, first got the function to return in the alert. Second got first 2 to alerts, then the last alert “User with ID 1 not found”

  15. larry Says:

    this was another helpful post from endusersharepoint http://www.endusersharepoint.com/2008/11/26/power-user-toolbox-javascript-for-sharepoint-pt5/
    I was able to get this to work like yours by adding a couple of fields

  16. Clint Says:

    I would be highly interested in how Larry was able to get the CEWP to show the proper information. I have the same issue with the error “user with ID1 not found” populating each field instead of the accounts information. I’ve run the same tests, all positive, listed above by Alexander as well. The same error with another user login as well (except saying user ID8 in this case). I’m working on toward your next article on hiding form fields based on user permissions and would really like to find this a working solution. I wouldn’t think testing through a VPN would make any difference. Thanks in advanced.

  17. Alexander Says:

    Hi Clint,
    I don’t know if Larry got this working, but i have one question that i newer asked Larry:
    Does your site collection reside in a managed path, or on the root URL?

    Alexander

  18. Clint Says:

    The site in question is on a managed path. This is being hosted on an SBS 2003 install with the standard ‘Company Web’ and such as well as a few administrative programs that have their own site hosting for making configuration changes (ex. SpiceWorks). This site is on the default \sites\ path. There is another site on the root but that seemed necessary to get the search function to work properly . . . It’s been awhile, but I clearly remember it being quite a pain. At any rate, yes this site is on a managed path.

  19. Alexander Says:

    Well, then i think the answer is to modify line 23 like this:
    wsBaseUrl = ‘/sites/_vti_bin/’;

    This is the path to where the web service “lists.asmx” is found.

    “sites” being the managed path of your site collection – modify as needed.

    Alexander

  20. Clint Says:

    Holy Syntax Batman!!

    You hit the nail on the head Alexander, thanks. Although I’m still new in scripting JQuery, I should have seen that one. After I changed the location to “/sites/main/_vti_bin” the script pulled the info in a heartbeat! I’ll be moving on to your next article on hiding fields based on user member ship. Thanks again, I’ll be sure to pass your blog on and add it to my list of good SharePoint resources :)

  21. Alexander Says:

    I’m glad it worked! -I will update the post to avoid similar problems.
    Alexander

  22. larry Says:

    @Alexander, I actually gave up on this script. I did not want to be a pest. I did however get another script to work, which is what I was referring to. Since I have seen the update here I went back to try and implement this again and much success. Thanks again. Now I can move on to the post that followed this one.

  23. Alexander Says:

    Did you update the script to address the “Managed path” and got it working?

    Alexander

  24. larry Says:

    Yes.

  25. larry Says:

    k, I am back playing with this script. two questions, first i’ll start with the easy one. When I run this script I dont have a Pic for my details, so I get red x for missing images. is there a way to show the default shadow image if a pic is missing?
    part 2, I have been trying to marry this script to another, manipulate SP fields for javascript. What I am trying to do is one of 2 things. either the form opens and reads who the user is, then populates several fields based off user information, or in a people/group field user selects a name, and that triggers several other fields (email.phone etc) to populate. Can this be done? I am thinking the a few more lines of code in your script should handle it, but when I add javascript I cannot get it to work. I am still learning jquery.

    I do appreciate all your efforts. have a great weekend

  26. Alexander Says:

    Hi,
    I have updated the code in the CEWP to have a default picture.

    Your other question is best answered by pointing you in he direction of the function “setFieldValue” from the file “fieldutility.js” found here:
    http://spjslib.codeplex.com/

    Alexander

Leave a Reply