Search This Blog

Friday, December 24, 2010

Calling Sharepoint Web Service through Javascript

Sharepoint 2010 has introduced Client Object Modal by which you can send a call to Sharepoint client API through code or through Javascript. But if you are calling the client API through Javascript, you can only do so by using asynchronous (executeQueryAsync) call to the native method.
Many a times you may need to get the data in the same method without leaving the control (means by a synchronous call without leaving the method). In that case, the best possible solution would be to use Web service calls.
Below is the code to accomplish this. For the sake of simplicity, I have called "Lists.asmx" web service to get an item by Id.

//Main Method
function GetItemByIdAndTitle(rootSiteUrl, ListTitle, itemId) {
var responseXML;
var ws;
try {
ws = InstanciateHttpRequest();
if (ws != null)
var soap = GetEnvelope(ListTitle, itemId); // create a web service envelope here"POST", rootSiteUrl + "/_vti_bin/lists.asmx", false);
ws.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
ws.setRequestHeader("SOAPAction", "");
if (ws.readyState == '4' && ws.status == '200')
responseXML = ws.responseXML.xml;
//you can parse your XML here to get the data
catch (e)
{ }
return responseXML;

//This ensures the the object instanciation is supported by multiple browsers // (Mozilla, IE).
function InstanciateHttpRequest()
var Obj;
if (window.XMLHttpRequest)
Obj = new XMLHttpRequest();
Obj = new ActiveXObject("Microsoft.XMLHTTP");
return Obj;

//Soap Envelope

function GetEnvelope(listName,itemId)
var soap = "<?xml version='1.0' encoding='utf-8'?>" +
"<soap:Envelope xmlns:xsi='' xmlns:xsd='' xmlns:soap=''>" +
"<soap:Body>" +
"<GetListItems xmlns=''>"+
"<listName>" + listName + "</listName>"+
"<query><Query><Where><Eq><FieldRef Name='ID' /><Value Type='Counter'>" + itemId + "</Value></Eq></Where></Query></query>" +
"<viewFields><ViewFields><FieldRef Name='ContentType' /></ViewFields></viewFields>" +
"<rowLimit>1</rowLimit>" +
"<queryOptions><QueryOptions><ViewAttributes Scope='Recursive'></ViewAttributes></QueryOptions></queryOptions>" +
"</soap:Body>" +
return soap;

You can change the soap envelope to get different data by calling other Sharepoint Web services.

No comments:

Post a Comment