Accessing Sharepoint lists with Javascript

July 11th, 2016

One of the more common programming requirements when working with Sharepoint is the ability to access lists that are stored on the server.  Normally this would be accomplished by using C# and creating a new Web Part to access the list.  But with more and more Sharepoint sites being hosted by Microsoft you might not always have the capability to publish a new Web Part.  Thankfully Microsoft now provides a complete Javascript API (JSOM or JavaScript Object Model) to manipulate data stored in Sharepoint.

 

Loading any client libraries

The first step in accessing the JSOM is to ensure that all the necessary libraries are loaded.  Because Sharepoint only includes libraries that are necessary for a page to function it is always a good idea to explicitly declare what libraries are needed.  In our case we only need one library named sp.js which will be used to get the Sharepoint context of the current site.  To load this library we make a call like this:

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

The Sharepoint method SP.SOD.executeFunc loads a library and then calls a method in that library.  In our case the library being loaded is sp.js and the method to be called is SP.ClientContext.  The third argument is a function that will be called after the initialization is complete.  This function is where you know in your script that the library has been loaded and that you have access to that library.  In our case this function means that the JSOM is loaded and we can begin to access data in Sharepoint.

 

Working with the page context

To start using the JSOM we have to first get an instance of the page context and get a reference to whatever list we want to access.  This can be accomplished with the following code:

var context = SP.ClientContext.get_current();
var list = context.get_web().get_lists().getByTitle('Sample List');

The next step is to tell Sharepoint how we want the list data returned to us.  This is done by creating a view for the list  using what is known as Collaborative Application Markup Language or CAML.  CAML is basically XML that defines the query used by Sharepoint to fetch our data.  Using CAML we can tell Sharepoint to order our list by a specific field, only return a certain number of list items, only include list items that match a specific criteria and so on.  To create the most basic CAML query and associate it with our list you would include the following code:

var caml = new SP.CamlQuery();
caml.set_viewXml('View><Query></Query></View>');
var listItems = list.getItems(caml);
context.load(listItems, 'Include(Title)');

The last line of this code tells the prepares the query in the page context and also tells Sharepoint which fields we want access to in the JSOM after the query is complete.   It is important to note that if you do not explicitly define what fields you want in this line you will not have access to them after the query is complete.

 

Actually loading the list data

Up until now all we have done is initialize the page context with the data that we want to pull from Sharepoint.  To actually query Sharepoint we need to call the executeQueryAsync method on our page context.  Since queries against Sharepoint are done asynchronously, this method provides two parameters:  a method to call on success and a method to call on failure.  An example of this call would be:

context.executeQueryAsync(
    Function.createDelegate(this, function() { // this is the success callback }),
    Function.createDelegate(this, function() { // this is the failure callback })
);

Inside of our success callback we finally have access to the list items and the field ‘Title’ that we had included in our query earlier:

var listEnumerator = listItems.getEnumerator();
while (listEnumerator.moveNext()) {
    var listItem = listEnumerator.get_current();
    var fieldValue = listItem.get_item('Title');
} 

 

Where to go from here

This example should be used to just show the starting point of how to load data from Sharepoint using Javascript.  Our CAML query returns all the list items and does no filtering which is almost never the case in a real world program.  A CAML query builder can be downloaded here that will allow you to connect to your Sharepoint site and build extremely complex queries using the lists and data that you may have already created.

 

And finally the code…


// load all necessary sharepoint javascript libaries
SP.SOD.executeFunc('sp.js', 'SP.ClientContext',	function () {

	// load the sharepoint list.
	loadSharepointList();
});

// loads the sharepoint list
function loadSharepointList() {

	// create the sharepoint content.
	var context = SP.ClientContext.get_current();
	
	// get the list by the title.
	var list = context.get_web().get_lists().getByTitle('Sample List');

	// create the query.
	var caml = new SP.CamlQuery();
	caml.set_viewXml(''); 
	
	// get the list items asynchronously
	var listItems = list.getItems(caml);
	context.load(listItems , 'Include(Title)');
	context.executeQueryAsync(
    
    	// success delegate
    	Function.createDelegate(this, function() {
    	
		// loop through the items.
	        var listEnumerator = listItems.getEnumerator();
	        while (listEnumerator.moveNext()) {
	        
	        	// get the current list item.
	        	var listItem = listEnumerator.get_current();
	        	
	        	// get the field value.
	        	var fieldValue = listItem.get_item('Title');
	        }
    	    	    	
    	}),
    	
    	// error delegate
    	Function.createDelegate(this, function() {
 			alert('Error fetching data from Sharepoint!');   	
    	}));

}

bswartz

Brian specializes in .Net and mobile software development at Accella. He graduated from Texas Tech University with a degree in computer science. While attending Texas Tech University, he took a job as a developer for a medical software company where he continued to work for 15 years. He specialized in developing interfaces for lab machines and clinical systems.

Leave a Reply

Categories