Write a simple JavaScript Object Model Script for SharePoint 2010

The SharePoint Client Object Model allows applications to make server calls to SharePoint, who originate from a server or system without SharePoint installed.

Server calls can include retrieving list items, updating list data, or even manipulating security. Note that there are some functions only available to the Server Object Model (such as interacting with Web Application and Farm objects).

I am going to demonstrate a simple example of retrieving information from the SPWeb and SPSite objects of the current site collection.  The example is using JavaScript to access the Client Object Model. For this example we create a Document Library called “Scripts,” to store our JavaScript files.  Create a new file called Test_CEWP.js and open it for editing.

The first part of this file is going to be a simple HTML content placeholder, to display the information on the page. Next we create our Script tags, where we will insert our JavaScript code:

<div id="contentDiv">&nbsp;</div>
<script type="text/javascript" language="javascript">
</script>

Before we start making server calls, we want to provide an update to the web part, to show it is loading.  The calls can be made asynchronously, so the rest of the page can load quickly.  Here we will set the HTML div content to “Loading…”:

<div id="contentDiv">&nbsp;</div>
<script type="text/javascript" language="javascript">
 var div = document.getElementById("contentDiv");
 div.innerHTML = "Loading...";
</script>

SharePoint includes JavaScript files to define and implement the Client Object Model API.  One of these files is called “SP.js.”  We need to make sure this script is loaded before our code.  This is part of the API.  We want the request to load asynchronously, so the rest of the page can load quickly.  Here we will set the HTML div content to “Loading…”:

<div id="contentDiv">&nbsp;</div>
<script type="text/javascript" language="javascript">
 var div = document.getElementById("contentDiv");
 div.innerHTML = "Loading...";
 ExecuteOrDelayUntilScriptLoaded(GetSite, "sp.js");
</script>

The function GetSite is going to be the name of our function.  We need a Context object to use to load data, and to interact with SharePoint.  The code below creates the GetSite() function, and returns an object which represents the SharePoint context of the current site:

<div id="contentDiv">&nbsp;</div>
<script type="text/javascript" language="javascript">
 var div = document.getElementById("contentDiv");
 div.innerHTML = "Loading...";
 ExecuteOrDelayUntilScriptLoaded(GetSite, "sp.js");
 function GetSite()
 {
  var ctx = new SP.ClientContext.get_current();
 }
</script>

Now we need to make a call to return the SPWeb object (an object representing the current web site).  Note this won’t actually be executed until we tell it to (see below, executeQueryAsync). We assign it to the current object to reference later.  This allows batch processing which can improve performance.

<div id="contentDiv">&nbsp;</div>
 <script type="text/javascript" language="javascript">
 var div = document.getElementById("contentDiv");
 div.innerHTML = "Loading...";
 ExecuteOrDelayUntilScriptLoaded(GetSite, "sp.js");
 function GetSite()
 {
 var ctx = new SP.ClientContext.get_current();
 this.web = ctx.get_web();
 ctx.load(this.web,'Title');
 }
 </script>

We can control which properties of an object are returned.  This can improve performance by only transferring relevant data. The above load method tells SharePoint to only return the Title property.  We could add as many parameters as we like.

The final call in this function is to execute the query.  It can be executed asynchronously, meaning other parts of the page can load while waiting for this call to be returned:

<div id="contentDiv">&nbsp;</div>
 <script type="text/javascript" language="javascript">
 var div = document.getElementById("contentDiv");
 div.innerHTML = "Loading...";
 ExecuteOrDelayUntilScriptLoaded(GetSite, "sp.js");
 function GetSite()
 {
 var ctx = new SP.ClientContext.get_current();
 this.web = ctx.get_web();
 ctx.load(this.web,'Title');
 ctx.executeQueryAsync(Function.createDelegate(this, this.onSiteLoadSuccess), Function.createDelegate(this, this.onSiteLoadFail));
 }
 </script>

The executeQueryAsync function intiates a call to the SharePoint server (asynchronously), and provides function delegates to invoke on success/failure.  See the two functions onSiteLoadSuccess and onSiteLoadFail in this example:

<div id="contentDiv">&nbsp;</div>
 <script type="text/javascript" language="javascript">
 var div = document.getElementById("contentDiv");
 div.innerHTML = "Loading...";
 ExecuteOrDelayUntilScriptLoaded(GetSite, "sp.js");
 function GetSite()
 {
 var ctx = new SP.ClientContext.get_current();
 this.web = ctx.get_web();
 ctx.load(this.web,'Title');
 ctx.executeQueryAsync(Function.createDelegate(this, this.onSiteLoadSuccess), Function.createDelegate(this, this.onSiteLoadFail));
 }
 function onSiteLoadSuccess(sender, args)
 {
 div.innerHTML = "<div>Title: " + this.web.get_title() + "</div>";
 }
 function onSiteLoadFail(sender, args)
 {
 div.innerHTML = "Error: " + args.get_message();
 }
 </script>

If the call is successful, the web site title is rendered inside the div element we setup above.  If an error occurs, the error message is displayed.

To try out the example, save the above JavaScript file (e.g. Test_CEWP.js), and upload it to your document library in SharePoint.

Copy the link to the script in the library to the clipboard.

Open and edit a sharepoint page.  Add a Content Editor Web Part and paste the URL copied previously into the source text property.

Click OK and you should see the JavaScript code run.

Notice this example required no administrative access, only access to a document library and adding a web part. The server call was asynchronous so other parts of the page can load while the call is being made.

Advertisements

One thought on “Write a simple JavaScript Object Model Script for SharePoint 2010

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