Click here to Skip to main content
15,860,972 members
Articles / Web Development / ASP.NET

SharePoint 2010: Client Object Model for JavaScript (ECMAScript)

Rate me:
Please Sign up or sign in to vote.
4.59/5 (9 votes)
21 Feb 2010CPOL6 min read 221.6K   24   5
SharePoint 2010 Client OM for JavaScript

As I said in my first post on Client Object Model (OM), there are three sets of Client OM: Managed .NET client, Silverlight and ECMAScript. Lately, I have posted an article on how to use Client OM from Managed .NET Client. Today, I’ll go through Client OM for JavaScript. ECMAScript Client OM is SharePoint 2010 client object model extension for using with JavaScript or JScript. Few points to notice about ECMAScript Client OM:

  • ECMAScript object model can only be used in SharePoint sites. So you can’t use this object model in an ASP.NET site to access SharePoint resources deployed in another URL as this is cross-site scripting and not allowed.
  • You can’t use this object model in a SharePoint site to access resources in different SharePoint sites (i.e., different URLs). For example, from mysite.mysp.com, you can access resources in yoursite.yoursp.com using ECMAScript client OM. This is also cross-site scripting.
  • You can use JQuery with ECMAScript Client OM and for this, you don’t need to do some extra work. All you need to do to use JQuery is to add reference to JQuery.js file and start using JQuery.
  • You can use this ECMAScript Client OM in web part pages or application pages (aspx pages) by referencing a JavaScript file (SP.js). You don’t need to add reference to the file manually rather use <SharePoint:ScriptLink Name=”sp.js” ………. />. The file is located on the path “Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\TEMPLATE\LAYOUTS”.
  • To update with JavaScript, you need to add a FormDigest tag in your page for security purpose. I’ll explain it later in detail.

Use ECMAScript Library

At first, use Visual Studio 2010 to create a SharePoint web part project. As a result, VS2010 will open an ascx control for you on the designer. 

1. Add Reference to js File

To use Client OM, add an entry like below in your web part ascx control. For your information, there’s a debug version of the sp.js called sp.debug.js which you can use for debugging, but should not be used in production.

XML
<SharePoint:ScriptLink Name="SP.js" runat="server" OnDemand="true" 
    Localizable="false" />

Here, OnDemand means whether the sp.js file needs to be loaded on demand (not in page load) or not.

2. Add FormDigest Tag

If your code modifies SharePoint content, add a FormDigest control inside your page. The FormDigest adds a security token inside your page based on user, site and time. Once the page is posted back, the security token is validated. Once the security token is generated, it’s valid for a configurable amount of time. Add the FormDigest inside <form>…</form> tag, as shown below:

XML
<SharePoint:FormDigest runat="server" />
For more information on FormDigest, follow the links below:

3. Use Client OM to Retrieve Data

Now you can use SharePoint ECMAScript library. Let's dissect the code snippet below. The first thing in using this library is that you need to get the ClientContext (just like SPContext). Then the context.get_web returns the current web (just like SPContext.Current.Web). Then, client context’s load method is invoked passing the web object. Then the executequery method is invoked asynchronously passing two functions: onSuccess and OnFailed which will be called on success and fail correspondingly.

JavaScript
<script type="text/javascript">
    function getWebProperties() {
        var ctx = new SP.ClientContext.get_current();
        this.web = ctx.get_web();
        ctx.load(this.web);
        ctx.executeQueryAsync(Function.createDelegate(this, this.onSuccess),
            Function.createDelegate(this, this.onFail));
    }
    function onSuccess(sender, args) {
        alert('web title:' + this.web.get_title() + '\n ID:' + this.web.get_id() + 
            '\n Created Date:' + this.web.get_created());
    }
    function onFail(sender, args) {
        alert('failed to get list. Error:'+args.get_message());
    }
</script>

By calling getWebProperties method from any web part, you can get the current web’s title, id and creation date.

4. Load Minimal Data You Need

In the above code snippet, the Ctx.load method is invoked with only one parameter (web). The load method will load all properties of the web object. But we are only using Id, Title and Created Date properties. If you know which properties you are interested in, you can pass the properties names in the load method and only those properties will be loaded. For example, the following load method will return only ID, Title and Created Date.

JavaScript
ctx.load(this.web,'Title','Id','Created');

Remember, here the properties names are properties of SPWeb. You need to pass Title instead of title. The properties name uses CAML casing. You can get the full lists of ECMAScript namespaces, object, properties following the link on MSDN. The document is not final yet and may be changed. You can also look into the sp.debug.js file in the folder “Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\TEMPLATE\LAYOUTS”, to get an idea of objects, properties and methods of ECMAScript Client OM.

5. Execute Your JavaScript Function after sp.js is Loaded

Sometimes, you may need to execute your JavaScript (that uses ECMAScript Client OM) on page load in the browser. But since your JavaScript is using sp.js file and if the sp.js file is not loaded yet (since to lazy loading nature of sp.js), when your custom JavaScript will be executing, you’ll get your JavaScript function not executed. In this case, you need to make sure your JavaScript code runs after sp.js finishes loading. You can do so by putting your JavaScript method call inside a js function as shown below:

JavaScript
ExecuteOrDelayUntilScriptLoaded(myjsfucntion, "sp.js");

Putting your JavaScript function (i.e., myjsfunction) inside the ExecuteOrDelyUntilScriptLoaded method delays your method call until the sp.js file is loaded.

6. Update with ECMAScript Library

You can use the Client OM to update SharePoint contents. The following code snippet shows how to update web title.

JavaScript
<script type="text/javascript">
    function updateTitle() {
        var ctx = new SP.ClientContext.get_current();
        this.web = ctx.get_web();
        web.set_title('UpdatedTitle');
        this.web.update();
        ctx.executeQueryAsync(Function.createDelegate(this, this.onUpdate),
            Function.createDelegate(this, this.onFail));
    }
    function onUpdate(sender, args) {
        alert('title updated');
    }
    function onFail(sender, args) {
        alert('failed to update title. Error:'+args.get_message());
    }
</script>

By calling the updateTitle method from any web part or SharePoint application pages, you can change the title of current web site (where the web part or application page is deployed). For your information, in ECMAScript Client OM, to get a property, use get_propertyName and to set a property use set_propertyName. To update list with ECMAScript library, you need to add FormDigest tag.

Use JQuery with ECMAScript

You can use JQuery with ECMAScript without any conflict. As usual, you need to add jquery.js file reference to your page/web part or in master page. Then you can use JQuery like normal ASP.NET applications. But make sure that if you need to execute any JavaScript function on page load event, you put this inside ExecuteOrDelayUntilScriptLoaded function.

Deployment Consideration

SharePoint provides two sets of JavaScript files: minified and unminified/debug version. For example, sp.js file is minified and sp.debug is minified and debug version. The default master page in SharePoint has a scriptmanager in the page and whose ScriptMode is set to auto, as a result, the minified version of js file loaded. If you want to use debug version, you can add the <deployment retail="false" /> in the <system.web> section of the web.config. In the production, you need to remove this entry to make sure minified version is used. The ECMAScript is supported in the following browsers:

  • Microsoft Internet Explorer 7.0 or greater
  • Firefox 3.5 or greater
  • Safari 4.0 or greater

More Information

To get the full list of namespaces and Classes, you can download the SharePoint 2010 SDK or you can follow the link on MSDN.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Architect ImpleVista Aps
Denmark Denmark
Sohel has more than six years of experience in professional software development with extensive involvement in Web based Object-Oriented, Multi-Tiered application design and development. He's Familiar with Test Driven Development (TDD) and refactoring techniques as well as having expertise in architecturing large enterprise applications. He has Experience in working with Content Management System and Portal Management System tools like SharePoint, DotNetNuke, Ektron.

Over last few years, he’s involved in development with projects on Microsoft SharePoint and received Microsoft MVP for SharePoint Server Development in the year 2011 and 2012. Currently he's working in a software company located Copenhagen,Denmark on a project integrating SharePoint and SAP. You can read his popular blog at: http://ranaictiu-technicalblog.blogspot.com

Comments and Discussions

 
GeneralMy vote of 5 Pin
Ali BaderEddin27-Sep-12 10:34
Ali BaderEddin27-Sep-12 10:34 
GeneralMy vote of 4 Pin
maratheguruprasad18-Jan-12 19:46
maratheguruprasad18-Jan-12 19:46 
GeneralMy vote of 3 Pin
Marsh Jariwala12-Jun-11 20:02
Marsh Jariwala12-Jun-11 20:02 
GeneralThanks Pin
Moustafa Arafa9-Jun-10 16:28
Moustafa Arafa9-Jun-10 16:28 
GeneralSharePoint 2010, Client Object Model Pin
praveen.batula4-Apr-10 9:59
praveen.batula4-Apr-10 9:59 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.