Click here to Skip to main content
15,891,607 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Can we call Web services on the client side using .NET proxy classes????
Posted

1 solution

Steps to call webservice using Ajax or JavaScript:

Step 1: Create XMLHttpRequest object. Given below method returns proper XMLHttpRequest object depending upon browser:

JavaScript
function CreateXMLHttpRequest() {
        if (typeof XMLHttpRequest != "undefined"){
            //All modern browsers (IE7+, Firefox, Chrome, Safari, and Opera) uses XMLHttpRequest object
            return new XMLHttpRequest();
     }
        else if (typeof ActiveXObject != "undefined") {
            // Internet Explorer (IE5 and IE6) uses an ActiveX object
            return new ActiveXObject("Microsoft.XMLHTTP");
     }
        else {
            throw new Error("XMLHttpRequestnot supported");
     }
    }


Step 2: Call open method and pass proper parameter as per the requirement

JavaScript
var objXMLHttpRequest = CreateXMLHttpRequest(); //Create XMLHttpRequest object
objXMLHttpRequest.open("POST", <serviceUrl>, false);

Open method accept three parameters, They are mentioned below:
method - Type of request, it can be GET or POST.
serviceUrl - Url of the webservice or page URL.
isAsync - It will be either 'true' or 'false'. Pass true to make asynchronus webservice call.

JavaScript
// Add mentioned below code if your application calls webservice Asynchronously.
objXMLHttpRequest.onreadystatechange = function (){
       if (objXMLHttpRequest.readyState ==4 && objXMLHttpRequest.status == 200){
             result = objXMLHttpRequest.responseXML;
       }
}
Step 3: Use "setRequestHeader" method to set header of the Http request. For example suppose we have to pass XML data to call webservice. Use mentioned below code:

JavaScript
objXMLHttpRequest.setRequestHeader("Content-Type","text/xml; charset=utf-8");
Note: Suppose you do not have to pass any thing in send method then no need set content-type.

Step 4: Finally we have to prepare packet and call send method. Be careful while creating packet because you make small mistake that can waste a lots of time in debugging.
HTML
var packet = '<?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>

   <WebMethodName xmlns="<Webservice Namespace>">

  <ParameterName>value</ParameterName>

  <ParameterName>value</ParameterName >

  <ParameterName>value</ParameterName>

  </WebMethodName>

     </soap:Body>  </soap:Envelope>';


We need to replace highlighted text with the proper value in the above packet before sending the xml http request. Purpose highlighted text are mentioned below:
WebMethodName - Webmethod name and method name is case sensitive.
<Webservice Namespace> - Namespace of webservice "http://SampleWebservice.com/"
e.g:[WebService(Namespace = "http://SampleWebservice.com/")]
ParameterName - Parameter Name of webmethod and its value
        objXMLHttpRequest.send(packet);

JavaScript
// Add mentioned below code if your application calls webservice synchronously.
       result = objXMLHttpRequest.responseXML;

Now we know how to call webservice using Ajax or JavaScript. Mentioned below sample code of a simple webservice and web-method call using Ajax.

Sample webservice code:
C#
/// <summary>
/// Summary description for SampelWebservice
/// </summary>
[WebService(Namespace= "http://SampleWebservice.com/")]
[WebServiceBinding(ConformsTo= WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
[System.Web.Script.Services.ScriptService]
public class SampelWebservice: System.Web.Services.WebService
{
    [WebMethod]
    public string HelloWorld(string text)
    {
        return text;
    }
}


Sample Code for webservice call:

JavaScript
var objXMLHttpRequest = CreateXMLHttpRequest();

objXMLHttpRequest.open("POST", "http://localhost/SampleWebservice.asmx", true);

objXMLHttpRequest.setRequestHeader("SOAPAction","http://SampleWebservice.com/HelloWorld");

var packet = '<?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>

   <HelloWorld xmlns="http://SampleWebservice.com/">

  <text> Asynchronous webservice call using Ajax</text>

  </WebMethodName>

     </soap:Body>

     </soap:Envelope>';



objXMLHttpRequest.onreadystatechange = function(){

       if (objXMLHttpRequest.readyState == 4 && objXMLHttpRequest.status == 200) {

            result= objXMLHttpRequest.resposeXML;

        }

}

objXMLHttpRequest.send(packet);


I hope, it will help you understand use of Ajax.
 
Share this answer
 
v2
Comments
Wendelius 19-Dec-11 12:51pm    
Modified for readability

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900