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
ws.open("POST", rootSiteUrl + "/_vti_bin/lists.asmx", false);
ws.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
ws.setRequestHeader("SOAPAction", "http://schemas.microsoft.com/sharepoint/soap/GetListItems");
ws.send(soap);
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();
}
else
{
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='http://www.w3.org/2001/XMLSchema-instance' xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/'>" +
"<soap:Body>" +
"<GetListItems xmlns='http://schemas.microsoft.com/sharepoint/soap/'>"+
"<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>" +
"</GetListItems>"+
"</soap:Body>" +
"</soap:Envelope>";
return soap;
>


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

No comments:

Post a Comment