Pages

Sunday, February 21, 2010

SharePoint 2010: Client Object Model for JavaScript (ECMAScript)

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 details.

 

Use ECMAScript Library

At first use Visual Studio 2010 to create a SharePoint web part project. As a result, VS2010 will open a 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 an debug version of the sp.js called sp.debug.js which you can use for debugging but should not be used in production.

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

Here, OnDemand means whether the sp.js file need 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 add 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:

<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. Lets 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.

<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.
 
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:

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.

<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 an 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 as 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 file: 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 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.

9 comments:

  1. very cool & good tip, thank you very much for sharing.

    ReplyDelete
  2. Good introduction.
    Here are some posts which I have written.

    Client Object Model: http://praveenbattula.blogspot.com/search/label/Client%20Object%20Model

    All SharePoint 2010: http://praveenbattula.blogspot.com/search/label/SharePoint%202010

    Samples and examples: http://praveenbattula.blogspot.com/2010/04/sharepoint-2010-managed-client-object.html

    thanks
    -Praveen.

    ReplyDelete
  3. Hi Sohel,

    I just wanted to say that I really enjoyed your blog and this post. You make some very informative points. Keep up the great work!

    -
    Sharepoint Developers

    ReplyDelete
  4. Sharepoint web sites typically do not adhere to the WCAG (Web Content Accessibility Guidelines) 1.0 specification.Sharepoint 2007 relied extensively on table-based layouts, especially in the Web Parts Framework. Sharepoint's built-in controls produce markup that does not validate under XHTML doctypes. Substantial custom development is necessary to comply with these standards.Sharepoint solutions are rare in situations where strict adherence to accessibility standards is required, such as the public sector.
    Sharepoint 2010 administration http://bit.ly/lrFAYC

    ReplyDelete
  5. Hi Sohel,
    Is there a way we can upload a file using this ECMA script? We have this option in c# client object model.

    ReplyDelete
  6. Hi Sirdar,
    Most probably (I'm not 100% sure) you can't use Ecmascript to upload file. Alternatively you can use webservice/wcf service.

    ReplyDelete
  7. I like your Post very much and It is very interesting. I will use this Info to Develop the SharePoint Applications. Thanks for share this valuable Information.

    ReplyDelete
  8. I Sohel i want to send mail using ECMA script is there any way please help

    ReplyDelete
  9. I write the same Javascript program, but its not working. Its deployed Successfully, but on clicking of the button its not displaying Title & Description. When I use the alert function for debugging i found that there is the problem in var ctx = new SP.ClientContext.get_current() cause i have put alert box before and after this line of code. The first alert box appear, but not second one. SO PLEASE CAN YOU HELP ME...

    ReplyDelete

Note: Only a member of this blog may post a comment.