Details: You must have already gone through the first part of this series (here) that would give you a very high overview of what is Client OM, why do we need it and its supporting features in SharePoint 2010. In this post lets see how to use Javascript to get my work done

Problem Case: I would like to first retreive the site name and then later I would like to change the site name to 'Hello Srini'. Everything using Client OM and JavaScript.

Details: Before we begin let learn few important factors about Client OM and Javascript.

You need to under the SharePoint context to use both COM / JS

You need to have reference to sp.js (found under _layouts folder). This is the core object library

You can use JQuery in conjunction with JS

You cannot use this script to do cross site references

Ok, lets get to some serious business here

Create a new SharePoint 2010 project (Farm Solution) - Why choose Farm Solution in this case? Just because I would like to use the UserControl in this example.

Open your VisualWebPart1UserControl.ascx and get to the source

Add the sp.js reference to the page (just after the default references on the control) - This is a js script link addition as show below

Copy paste the below code below the script link reference

And finally add 2 html buttons to call the java script methods that we created in previous step.

Right click on the project and use the 'deploy' option.

Once successful, go to your SharePoint site and either create a new page or just use exisitng home page.

Edit the page and drag and drop the newly created webpart (from the Custom section)

Save and Exit. View the output.

lets now understand the code little bit.

SP.ClientContext.get_current() provides us with the current sharepoint context as in SPContext.Current (Server API)

context.get_web would retreive the web object // equivalent to SPWeb

context.load(web) // mark this line; you will notice the usage everywhere. When you execute this line, the web object is full loaded to the client context

context.executeQueryAsyn(SucessDelegate, FailerDelegate) // We need to construct 2 delegates - one for Success return and other for failure return. Both ECMA and Silverlight scipts need these Async Callback mechanisms.

web.set_title() // This would basically set the title of the web

web.update() // finally updates the web after all changes are successfully completed.