Sunday, May 27, 2007

Ways of using Web service from JavaScript


1. Client side <--> ASPX page <--> Web service.
2. Client side <--> HTC file <--> Web service.
3. Client side <--> AJAX <--> Web service.
4. Client side <--> SOAP Request/Response <--> Web service.


1. Create a dummy aspx page that is used by JavaScript to use Web Service functions. JavaScript class calls aspx page and in turn aspx page calls Web Service. Here aspx page use Web Service by adding a Web Reference in project and create a object of Web Service class and process it as normal function calling.


2. HTC Usage –


HTML Page ----



<body>
<div id="service" style="behavior: url(webservice.htc)">

-------------
-------------

</body>





Java Script File ----



function asyncWSCall(strMethodName, strCountryName, boolAsync)
{
strMethodName == "getCurrentPositionData" ; //WebService function name

// Establish the friendly name "WS" for the WebServiceURL
//service.useService("http://localhost/DemoApp/SampleWebService.asmx?WSDL","WS");

// The following uses a callback handler named " processgetCurrentPositionData"
iCallID = service.WS.callService(processgetCurrentPositionData,
strMethodName, strCountryName, boolAsync);
}


function processgetCurrentPositionData(result)
{
-------
-------

document.getElementById('txtAr').value = result.value.xml;
}




Web Service ----


[WebMethod]
public XmlDocument getCurrentPositionData(string countryName, bool boolAsync)
{
------
------
}




3. AJAX Usage –

HTML Page ----


<body>
<form id="form1" runat="server">
<asp:ScriptManager runat="server" ID="scriptManagerId">
<services>
<asp:ServiceReference Path="WSForAJAX.asmx" />
</services>
</asp:ScriptManager>

-----
-----

</body>




Java Script File ----



function wsCallForCurrentPostion()
{
WSForAJAX.getCurrentPositionData(OnSucceededWithContext, OnFailed,"XmlDocument");
}



// This is the callback function invoked if the Web service succeeded.
// It accepts the result object, the user context, and the calling method name as parameters.
function OnSucceededWithContext(result, userContext, methodName)
{
var RsltElem = document.getElementById('txtAr').value;

var readResult;
if (userContext == "XmlDocument")
{
if (document.all)
readResult = result.documentElement.firstChild.text;
else // Firefox
readResult = result.documentElement.firstChild.textContent;

RsltElem.innerHTML = "XmlDocument content: " + readResult;
}
}



// This is the callback function invoked if the Web service failed.
// It accepts the error object as a parameter.
function OnFailed(error)
{
// Display the error.
var RsltElem = document.getElementById("ResultId");
RsltElem.innerHTML = "Service Error: " + error.get_message();
}




Web Service ----



[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Xml)]
public XmlDocument getCurrentPositionData(string countryName, bool boolAsync)
{
----
----
}




4. SOAP Usage –


Java Script File ----



//Function to create parameter for WebService method.
function createWSParam()
{
var strMethodName = 'getCurrentPositionData' ;
var strSoapContent = '<countryName>' + count4WSCall + '</ countryName >\n'
+ '<boolAsync>' + strCountryName + '</ boolAsync >\n' ;
}





//Function to create SOAP data packet.
function createSOAPData(strMethodName, strSoapContent)
{
var soapAction = 'http://tempuri.org/' + strMethodName ;
var url = 'http://localhost/DemoApp/SampleWebService.asmx' ;
var data = '<?xml version=\'1.0\' encoding=\'utf-8\'?>\n'
+'<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/\'>\n'
+ '<soap:Body>\n'
+ '<' + strMethodName + ' xmlns=\'http://tempuri.org/\'>\n'
+ strSoapContent
+ '</' + strMethodName + '>\n'
+ '</soap:Body>\n'
+'</soap:Envelope>' ;
}





//Function to create XMLHttpRequest.
function getXmlHttpObject()
{
var xmlhttp ;
if(window.ActiveXObject)
{
try
{
xmlhttp = new ActiveXObject('Msxml2.XMLHTTP');
}
catch (ex)
{
xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');
}
}
else if (window.XMLHttpRequest) //For Non-IE
{
xmlhttp = new XMLHttpRequest();
}
}





//Function to send the SOAP Request.
function sendSOAPDataToWebService(xmlhttp, url, data, soapAction)
{
xmlhttp.open('POST', url, true);
xmlhttp.onreadystatechange = processgetSOAPResponseData ;
xmlhttp.setRequestHeader('Content-Type', 'text/xml');
xmlhttp.setRequestHeader('SOAPAction', soapAction);
xmlhttp.send(data);
}





//Function to process the SOAP Response.
function processgetSOAPResponseData()
{
if (xmlhttp.readyState == 4)
{
if (xmlhttp.status == 200) // only if "OK"
{
try
{
if (window.ActiveXObject) // code for IE
{
doc = new ActiveXObject("Microsoft.XMLDOM");

doc.async="false";
doc.loadXML(xmlhttp.responseText);
}
else // code for Mozilla, Firefox, Opera, etc.
{
var parser=new DOMParser();
doc = parser.parseFromString(xmlhttp.responseText,"text/xml");
}

var rootNode = doc.documentElement;
// documentElement always represents the root node

if( rootNode.childNodes[0].childNodes[0].childNodes[0].nodeName
== "getCurrentPositionDataResult" )
{
//Method to process the SOAP data
getCurrentPositionData(rootNode) ;
}
}
catch (ex)
{
}
}
}
}



Web Service ----



[WebMethod]
public XmlDocument getCurrentPositionData(string countryName, bool boolAsync)
{
------
------
}








Suggested Links:

AJAX Example
http://ajax.asp.net/docs/ViewSample.aspx?sref=Sys.Net.SimpleWebService/cs/SimpleWebService.asmx

Use of Xml in AJAX
http://ajax.asp.net/docs/tutorials/CreateSimpleAJAXApplication.aspx
http://ajax.asp.net/docs/ViewSample.aspx?sref=EnhancingJavaScript/cs/Inheritance.aspx

HTC -
http://msdn.microsoft.com/archive/default.asp?url=/archive/en-us/samples/internet/behaviors/library/webservice/default.asp

HTC Example -
http://msdn2.microsoft.com/en-us/library/ms531033.aspx

HTC Result Object example --
http://msdn2.microsoft.com/en-us/library/ms531058.aspx

No comments:

Google