JavaScript Client Object Model in SharePoint 2013

SharePoint 2013 has a new and more complete JavaScript Client Object Model API. Some of the additional functionality is using social networking.

Using the JS COM, followers can be pulled from SharePoint for the current user or a specific user. This might be used for creating a new social networking interface

My Followers

First load JQuery and the SharePoint 2013 JavaScript functions. The JavaScript functions are loaded on the page so it is just a case of waiting for specific functions to be loaded before the script will work correctly (see below):

SP.SOD.executeFunc('sp.js', 'SP.ClientContext', function () {
	SP.SOD.executeFunc('userprofile', 'SP.UserProfiles', function () {
		tonyishereGetUserProfileProperties();
	});
});

Once the functions are loaded, the People manager object can be created. The example below was taken from the Micrsoft site and modified, this is a great resource if you are starting out with the client object model.

http://msdn.microsoft.com/en-us/library/office/jj679673.aspx

function tonyishereGetUserProfileProperties() {
    // Get the current client context.
    var clientContext = SP.ClientContext.get_current();
    // Get the PeopleManager instance.
    var peopleManager = new SP.UserProfiles.PeopleManager(clientContext);
    // Get the people who are following the current user.
    Followers = peopleManager.getMyFollowers();
    clientContext.load(Followers);
    // Send the request to the server.
    clientContext.executeQueryAsync(displayFollowers, requestFailed)
}

Once the object has been loaded successfully, functions can be run to pull out the required data. In the example below, the data is stored in a string which is then displayed as HTML in a div using JQuery.

function displayFollowers() {
    var results = Followers.getEnumerator();
	var myFollowers = "Followers<br />";
    while (results.moveNext()) {
    var person = results.get_current();
		myFollowers = myFollowers + "<br />" + person.get_displayName();
    }
	jQuery("#MyFollowers").html(myFollowers);
}

The script was added to the page without the use of Visual Studio or SharePoint Designer 2013. The script was inserted using the Script Editor web part. This web part runs client side code such as HTML and JavaScript.

Script Editor

The same methods can be used to pull out a whole host of data from the social aspects of SharePoint 2013 including the profile picture, display name, hash tags and trending topics.

Profile web part

Leave a Reply

Your email address will not be published. Required fields are marked *