Accessing user profile information in WSS 3.0 with javascript


18.09.2011 I have posted a new solution which makes this one obsolete. You find the new one here


09.09.2010 Updated the function “getUserInfo”. It no longer requires the list GUID for the user list to be specified in the script.

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.

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
 * ---------------------------------------------

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);
*/

function getUserInfo(UserId){
wsBaseUrl = '/_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('UserInfo',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.

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

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

  1. 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

  2. Bhavesha Says:

    Hello Alexander,

    Can u please send me the stringBuffer.js and interaction.js file ?
    Help is highly appreciated.

    Regards.
    Bhavesha

    • Alexander Says:

      Hi,
      The files are found here:
      http://spjslib.codeplex.com/.

      It is not me who have made these scripts, and i feel it it right that you get the files from the author directly.

      Sorry for the inconvenience, but to honor the author, please visit his site and download them from there.

      Alexander

  3. Jan Says:

    hi,

    is it possible to display information of a client and not of the current user?

    the name of the client stands in the field “client” in dispform.aspx.

    thanks

    • larry Says:

      Jan,
      there are several ways to prepopulate fields on the “NewForm”. One of the simplest is least secure is through the use of query strings.

      The DispForm should already have existing data which would make is easier to manipulate.

      Can you provide more details of what you’re trying to do?

    • Alexander Says:

      Get the userId from the “client” field in dispForm like this:

      <script type="text/javascript" src="../../Javascript/jquery-1.3.2.min.js"></script>
      <script type="text/javascript">
      fields = init_fields();
      // Find the userId from a people picker in DispForm
      var userIdRaw = $(fields['client']).find('.ms-formbody a').attr('href');
      var userId = userIdRaw.substring(userIdRaw.indexOf('=')+1);
      // Here is the userId for the person in the people picker
      alert(userId);
      
      function init_fields(){
        var res = {};
        $("td.ms-formbody").each(function(){
      	  if($(this).html().indexOf('FieldInternalName="')<0) return;	
      	  var start = $(this).html().indexOf('FieldInternalName="')+19;
      	  var stopp = $(this).html().indexOf('FieldType="')-7; 
      	  var nm = $(this).html().substring(start,stopp);
      	  res[nm] = this.parentNode;
        });
        return res;
      }
      </script>
      

      The “Show field:” in list settings for the people picker must be one of the “Name” options as this script gets the id from the link to the User information page.

      Alexander

  4. Filter list view based on membership in SharePoint group « SharePoint JavaScripts Says:

    [...] The script “AccessUserProfileInWSS.js” is found here. [...]

  5. Jan Says:

    thanks for your help.
    now it works.

    jan

  6. Uma Says:

    You are absolutely awesome Alex. So helpful to all of us. Thank you for the great work!

  7. Stacey Says:

    I have a question about this comment:

    // If your site collection resides on a managed path, “wsBaseUrl” must reflect the root of your site collection like this:

    25 // wsBaseUrl = ‘/myManagedPath/_vti_bin/’;

    I’m new to this, so I appoligize if this is a dumb quesiton… how do I know if my site resides on a managed path?

  8. Marc Says:

    Great, working like a charm, also with sharepoint foundation.
    Thank you very much

  9. Ian Says:

    I’ve been using this previously and it’s great. :-)

    I notice that you now say that list ID isn’t necessary, but I’ve a bit confused about what you mean:-

    “Define userListGuid (list guid of the user list on your root site) as variable accessible to this script”.

    Where do I declare that?

    Also, in my set up there’s different “people and groups” lists used for different sites. Is there one overall one I can access, or do I need to update it depending on which site the app’s running on?

    Also, the managed path reference seems to have gone. Is that not needed any more, or I am missing it somewhere?

    Thanks.

    • Alexander Says:

      Hi,
      After the update 09.09.2010 i didn’t remove all traces of the “list GUID requirements”. I have removed them now – Thank you for noticing!

      Managed path is no longer an issue.

      In a site collection there are only one “Userinfo list”. Even if a subsite do not inherit security, all users and groups are defined in the site collection root.

      Alexander

  10. Ian Says:

    I got a bit confused by the rating system and seem to have rated my own comment. I finally figured out you vote for the article by clicking on the stars at the top. I assumed that was just a display originally.

  11. Christianne Says:

    Hi,

    This scripts is exactly what I was looking for (and I lost count of how many I looked before)!! But I must have done something wrong because the user information that is showing is not mine.. Any ideas?

    And have you posted already the article about the membership?

    Thanks!

    • Alexander Says:

      Hi,
      I need some more information here:
      1. Do you get a completely random result, or do you get the same result every time (the same person)?

      2. Is it 2007 or 2010?

      3. Is the site on a managed path?

      Anything else that might be worth mentioning?

      Alexander

    • Christianne Says:

      Thanks for the reply.
      1. I always get the same result. Each person that logs in get a single user, but also not the correct user.
      2. It’s 2007
      3. Yes

    • Alexander Says:

      Could you please try to replace the text ‘UserInfo’ in line 25 in the code with the actual list GUID of the user list.

      To get the GUID, go to the “People and groups” list, right click – view source – search for ctx.listName.

      Alexander

  12. Wylaryzel Says:

    Dear Alexander,

    I had the same issue Christianne mentioned before – my subsite is on a managed path. I tried with alerts in the script and identified that the ID of the subsite on a managed path can have a different meaning on the mastersite. I had still a copy of the old sourcecode of your script and added the listname and the managed path and it was working like a charm :-)

    I don’t have access to the master site information, therefore I don’t know the exact reason for the difference.

    BR
    Wyl

    • Alexander Bautz Says:

      Hi,
      Managed paths always make things a bit harder… To have this script pull information from the right list when on a managed path, change the wsBaseUrl in line 20 like this:
      /myManagedPath/_vti_bin/

      Alexander

  13. Foster Says:

    Hi Alex,

    Great post (this and the related on on filtering views by group). I have 2 questions. The first is about security: do all authenticated users, even very limited ones, have access to the lists API via this sort of client-side scripting? Also, in 2010 (I realize you’re not explicitly supporting it) getItemById is returning null for all users I’ve tried (administrators mostly). I tried replacing the UserInfo reference with the GUID from _layouts/people.aspx.

    This is all related to 2010, so I may be swimming in my own creek.

    • Alexander Bautz Says:

      I think it would be available for all users, but it depends upon the configuration. It have to be tested in your local setup to be sure.

      This code should work in both 2007 and 2010, but might be a bit tricky if your site resides on a managed path.

      Can you provide some more info? – if possible, send me some screenshots.

      You find my email here

      Alexander

  14. Paul Says:

    I liked this article. It helped me get the user profile properties. I’m now trying to display them within a content editor web part. But when I placed the “document.write” command in there, it shows only a white screen with my text. The rest of my SharePoint page does not appear.

    It’s frustrating. All I want to do is display the text. I look on jquery.com and other places and I find examples for all sorts of complicated things but not displaying text. I don’t want to do an alert window either.

    Paul

    • Alexander Bautz Says:

      Hi,
      Add a div in the top of the CEWP like this

      <div id="myPlaceHolder"></div>
      

      Then change the line with document.write like this:

      $("#myPlaceHolder").html(str)
      

      Alexander

  15. Paul Says:

    Alexander, that sounds like it should work, but the text that I want to appear does not appear. I may have a Javascript error. Let me debug it and get back to you. Thanks.

    Paul

  16. Brijesh Shah Says:

    Hi Team,
    Can you tell me what is standard CEWP ? Where i can get that ? What webpart i can add in my page and write this javascript to check ?

    Please give me the answer here or email me. It’s really appreciable if you can help me quickly..

    • Alexander Bautz Says:

      Hi, The CEWP is the Content Editor Web Part that is shipped with both WSS, MOSS and SP2010. Edit page and insert it into any webpage.

      Alexander

  17. Brijesh Shah Says:

    Hi Alexander,

    Wow I have checked my installed Sharepoint 2007. But there is no such webpart. I found Picture and other webpart but not this one.
    Can you tell me from where i can add this content editor webpart in my sharepoint 2007 ? Or something i need to active or like ?

    • Alexander Bautz Says:

      You should find it under the “Miscellaneous” section. If you do not find it, it may have been removed by your server administrator.

      Alexander

  18. testuser Says:

    Hi,

    thanks for the code and it worked with current user.
    But when i gave other user id like (domain\\userid) it is returning the user is not found.
    I tried with different ids but the same result.
    Kindly help me out in this

    • Alexander Bautz Says:

      HI,
      The code found in this page does not support getting the user by login name. Follow the link to the new version in the top of this article.

      Alexander

  19. Accessing user profile information in SharePoint with javascript – updated version « SharePoint JavaScripts Says:

    [...] Accessing user profile information in SharePoint with javascript – updated version I have previously posted a solution for pulling user information from the built-in user information list in SharePoint (found in WSS 3.0, MOSS 2007 and SharePoint 2010 both foundation and server). This is NOT the user profile found in MOSS 2007 and in SharePoint 2010 server. You find the solution here [...]

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s


Follow

Get every new post delivered to your Inbox.

Join 435 other followers