Using the ECMAscript/JavaScript Client Object Model to read lists in SharePoint 2010

The new Client Object Model in SharePoint 2010 is awesome. Well, awesome for front end developers like us, who do mostly branding and some C# based web parts for our customers. On intranet projects it enables us to use our JavaScript skills to rapidly develop custom web parts for our clients with little or no need for compiled code, and brings that AJAX-like, web 2.0 feel that is very popular in web based applications these days. The premise is simple, use one function to prepare your list query, then execute it asynchronously, then call one or another function depending on whether the call succeeded or failed. It’s a round-trip to the server, so it’s best to only get the fields from the list that you actually need, and to implement request batching if you are going to be doing a lot of it, but here’s a simple example of reading a list to get you started. Note that OOTB this works for authenticated users only, the get_lists function is restricted by default to anonymous users. This can be changed, but research needs to be done in to the security reasons for it being turned off in the first place before you do.

First, a function that does the list querying:

function getTheList() {
 // get the list by it's name from the root site level
// Get the current client context to start. Most things run from the client context.
 clientContext = new SP.ClientContext.get_current();
// traverse up through the site to the root level, and get the list called 'my-list'.
// the root level isn't required, you can get a list from your current site level if you want, just use get_web() instead of get_site().get_rootWeb()
 var myList = clientContext.get_site().get_rootWeb().get_lists().getByTitle('my-list');
// use a standard syntax CAML query to filter your results and the fields returned if required, by adding the following, or passing parameters to the load command below
var query = new SP.CamlQuery();
// You can leave out this line if you just want to return the entire list.
query.set_viewXml('<View><Query><Where><Eq><FieldRef Name="myField"/><Value Type="Text">myValue</Value></Eq></Where></Query><ViewFields><FieldRef Name="myField1"/><FieldRef Name="myField2"/></ViewFields></View>');
// add your query to the getItems command for your list
this.collListItems = myList.getItems(query);
// issue the load command, these can be batched for multiple operations
// execute the actual query against the server, and pass the objects we have created to either a success or failure function
 clientContext.executeQueryAsync(Function.createDelegate(this, this.mySuccessFunction), Function.createDelegate(this, this.myFailFunction));
Next, create functions that deal with both the success and failure state of your list read request.
function mySuccessFunction() {
 // Do something useful like loop through your returned list items and output them somewhere
// create an enumerator to loop through the list with
 var listItemEnumerator = this.collListItems.getEnumerator();
// loop through the list items
 while (listItemEnumerator.moveNext()) {
 var oListItem = listItemEnumerator.get_current();
// do something with this here. Coupled with a platform like jQuery, you could do all kinds of great things
 strHtml += oListItem.get_item('myField1');
 // output your html somewhere here.
 function myFailFunction() {
 // do something to alert the user as to the error here.
Ok, so we have got the functions to read and output our list, so all that remains is to run them. SharePoint 2010 has a variety of options to manage how it loads its core javascript files, so also provides a useful helper function to enable us to only call our function once the Client Object model is full available, so after our functions we include the ExecuteOrDelayUntilScriptLoaded function call to initialise the first function only once the sp.js file has loaded;
ExecuteOrDelayUntilScriptLoaded(getTheList, "sp.js");

Leave a Reply

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

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

Google photo

You are commenting using your Google 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

This site uses Akismet to reduce spam. Learn how your comment data is processed.