Using the SharePoint 2010 Client Object Model in JavaScript

misc4_bgI just finished a task of creating a SharePoint page that involved heavy use of the SharePoint 2010 JavaScript Client Object Model (COM). While there is plenty of documentation for the SharePoint Client Object Model for Managed Code and Silverlight, there is a lot less available for using the COM with JavaScript. For the remainder of this post, I will use the term COM to refer to the SharePoint Client Object Model.

In this post, I will explain the benefits of using the COM with JavaScript and then go over the basics required to connect to a SharePoint site to do the following.

Why use the SharePoint Client Object Model for JavaScript?

Using the COM allows developers to create a web page that can interact with SharePoint without requiring a page refresh. In the background, the page uses JavaScript to communicate with SharePoint via the COM to retrieve or update data in SharePoint. JavaScript can then update the page to reflect the updated data from SharePoint.

Accessing SharePoint

The first thing to note about the COM with JavaScript is that it is disconnected from SharePoint in the sense that in order to retrieve or update data in SharePoint, asynchronous calls to the server must be made. Because of its asynchronous nature, the page can continue to be responsive to the user while the data is being retrieved or updated in the background. This can be both an asset and a liability if not handled properly.

In order to access the COM in a webpage, a reference to the JavaScript file containing the COM code must be included. There are 3 JavaScript files which contain the code for the COM: SP.js, SP.Core.js, and SP.Runtime.js. SharePoint provides the SharePoint:ScriptLink server control tag for referencing JavaScript files. Using the ScriptLink control will:

  • assure that the JavaScript file is loaded only once
  • assure that dependency files are also loaded

In a SharePoint Application page, the ScriptLink tag should be declared within the PlaceHolderAdditionalPageHead Content Placeholder.

<asp:Content ID=”PageHead” ContentPlaceHolderID=”PlaceHolderAdditionalPageHead” runat=”server” />
   <SharePoint:ScriptLink Name=”SP.js” LoadAfterUI=”true” runat=”server” />
</asp:Content>

How to Retrieve a ListItem from a SharePoint List

The following code sample shows how to connect to create a connection to SharePoint and access the Root Web.

var ListItem;

function GetListItemById(listName, listItemId)
{
   var SPContext = new SP.ClientContext.get_current();
   var web = SPContext.get_web();

   var list = web.get_lists().getByTitle(listName);
ListItem = list.getItemById(listItemId);

   SPContext.load(ListItem, “Id”, “Title”);
   SPContext.executeQueryAsync(GetListItemById_Success, GetListItemById_Fail);
}

function GetListItemById_Success(sender, args)
{
   var id = ListItem.get_id();
   var title = ListItem.get_item(“Title”);
alert(“Updated List Item: \n Id: “ + id + ” \n Title: “ + title);
}

// Display an appropriate error message
function GetListItemById_Fail(sender, args)
{
alert(“GetListItemById Failed. \n” + args.get_message() + “\n” + args.get_stackTrace());
}
Let’s break down the code. First, we declare a global variable which will contain the data returned from SharePoint via the COM. Since we must use asynchronous calls to SharePoint, the data must be stored somewhere that is accessible by the CallBack function that will be called once the data has been retrieved from SharePoint.

var SPContext = new SP.ClientContext.get_current();

Next, the code creates an object which will facilitate the communication between JavaScript and SharePoint. This is done by accessing the current property of the SP.ClientContext object by calling the get_current() method.

Note: In JavaScript, COM properties are access by calling a function which is named “get_” + the name of the property. For example, the id property which all COM objects have is accessed by calling the object’s get_id() method.

var web = SPContext.get_web();
var list = web.get_lists().getByTitle(listName);

Next, the Root Web property of the SPClientContext object can be accessed by calling the get_web() method. The Web has a SharePoint Lists collection property which is accessed by calling get_lists() method.

ListItem = list.getItemById(listItemId);

Then to identify the specific List, a call is made to the getByTitle() method passing in the name of the List. Finally, to identify a specific List Item in the List, a call is made to the getItemById() method passing in the List Item’s ID value.

At this point, there still has been no data retrieved from SharePoint. The code has simply been identifying which data will be retrieved.

Since it is the List Item data that will be retrieved and accessed in the CallBack function, it must be assigned to a global variable that can be accessed later by the CallBack function.

SPContext.load(ListItem, “Id”, “Title”);

Now that the specific data to be retrieved has been identified, we need to tell it specifically what data to return. It is the client context object’s load() method which specifies which data will be retrieved. The load() method’s first parameter is the object to return data for, followed by the names of the List Fields to return.

Note: While it is possible to call the load() method without specifying the List Fields, this will return data for every Field in the List, including hidden fields. Since loading all of the List Fields can add 10 times the amount of data needed, it will always be in your best interest to specify the specific Fields to load.

SPContext.executeQueryAsync(GetListItemById_Success, GetListItemById_Fail);

Finally, a call to the executeQueryAsync() method will initiate the actual call to the server. This method takes the 2 CallBack functions to call. The first will be called if the data is successfully retrieved from SharePoint, while the second will be called in the case there was an error retrieving the data.

function GetListItemById_Success(sender, args)
function GetListItemById_Fail(sender, args)

Each CallBack function can take the sender and args parameters which return additional information about the results of the server call.

var id = ListItem.get_id();
var title = ListItem.get_item(“Title”);

In the “success” CallBack function, the objects and their properties which were specified in the load() method can now be accessed using the object’s get_item() method passing in the name of the field.

How to create a ListItem in a SharePoint List

function CreateListItem(listName, title)
{
   var SPContext = new SP.ClientContext.get_current();
   var web = SPContext.get_web();

// Create a new List Item

   var SPContext = new SP.ClientContext.get_current();
   var list = web.get_lists().getByTitle(listName);
ListItem = list.addItem(new SP.ListCreationInformation());
ListItem.set_item(“Title”, title);
ListItem.update();

   SPContext.executeQueryAsync(CreateListItem_Success, CreateListItem_Fail);
}

function CreateListItem_Success(sender, args)
{
alert(“New List Item Created”);
}

// Display an appropriate error message
function CreateListItem_Fail(sender, args)
{
alert(“CreateListItem Failed. \n” + args.get_message() + “\n” + args.get_stackTrace());
}
This example is very similar to the previous one, so I will only point out the differences.

ListItem = list.addItem(new SP.ListCreationInformation());
ListItem.set_item(“Title”, title);

Once the List has been identified, a new List Item is created and added to the List. This is done by creating an instance of the SP.ListCreationInformation class. Then the properties of the new List Item object are set by using the set_item() method passing in the name of the property and the value to set it to.

ListItem.update();
SPContext.executeQueryAsync(CreateListItem_Success, CreateListItem_Fail);

The update() method is called to tell SharePoint to save the changes that were made. Finally the call to executeQueryAsync() method is made to send the request to SharePoint.

Note: In this example, the load() method was not called, and therefore there will not be any SharePoint data accessible in the “success” CallBack function. However, the load() method could have been called. In which case, the newly created List Item would be available.

How to update a ListItem in a SharePoint List

function UpdateListItem(listName, title)
{
   var SPContext = new SP.ClientContext.get_current();
   var web = SPContext.get_web();

   var list = web.get_lists().getByTitle(listName);
ListItem = list.getItemById(listItemId);

// Update an existing List Item
ListItem.set_item(“Title”, title);
ListItem.update();
   SPContext.executeQueryAsync(UpdateListItem_Success, UpdateListItem_Fail);
}

function UpdateListItem_Success(sender, args)
{
alert(“List Item Updated”);
}

// Display an appropriate error message
function UpdateListItem_Fail(sender, args)
{
alert(“UpdateListItem Failed. \n” + args.get_message() + “\n” + args.get_stackTrace());
}

Updating a List Item is simply a combination of identifying an existing List Item as seen in the first example and then setting the property values of the List Item as seen in the second example.

Again, if we actually want to access the values of the List Item as stored in SharePoint after it is updated, a call to the load() method could be made specifying the objects and their fields to retrieve from SharePoint.

How to delete a ListItem from a SharePoint List

function DeleteListItem(listName, title)
{
   var SPContext = new SP.ClientContext.get_current();
   var web = SPContext.get_web();

   // Retrieve the List Item
   var list = web.get_lists().getByTitle(listName);
ListItem = list.getItemById(listItemId);

   // Delete the List Item
   ListItem.deleteObject();
SPContext.executeQueryAsync(DeleteListItem_Success, DeleteListItem_Fail);
}

function DeleteListItem_Success(sender, args)
{
alert(“List Item Deleted”);
}

// Display an appropriate error message
function DeleteListItem_Fail(sender, args)
{
alert(“DeleteListItem Failed. \n” + args.get_message() + “\n” + args.get_stackTrace());
}
Again, deleting a List Item is very similar. In order to delete a List Item, the List Item must first be identified as in the first example and then a call made to its deleteObject() method to tell SharePoint to delete the List Item. Finally a call to the executeQueryAsync() method to send the updates to SharePoint.

6 thoughts on “Using the SharePoint 2010 Client Object Model in JavaScript

  1. Since sometime, was looking at using the Client side object model with Javascript all on the client. This is the first good example I have seen .. Good!

    Like

  2. I was having issues when using this function from a loop, until I changed:

    ListItem = list.getItemById(listItemId);

    to

    var ListItem = list.getItemById(listItemId);

    Like

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 )

Google+ photo

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

Connecting to %s