Click here to Skip to main content
Licence CPOL
First Posted 18 Jul 2008
Views 29,485
Bookmarked 29 times

Calling a Web Service from an HTML page using AJAX and HTTP POST (for all browsers)

By okdone | 15 Sep 2008
How to call a Web Service from an HTML page using AJAX and HTTP POST (for all browsers).
2 votes, 25.0%
1
4 votes, 50.0%
2
1 vote, 12.5%
3

4
1 vote, 12.5%
5
2.06/5 - 8 votes
μ 2.06, σa 2.24 [?]

Introduction

This article explains how you can call a Web Service using simple JavaScript and AJAX. This article discusses the client-side aspect. For the server-side aspect and source code, please visit this link.

Background

We can consume a Web Service from an HTML page using:

  1. The webservice.htc approach for Internet Explorer.
  2. Something like this: we include the above behaviour file like this:

    <div id="handle" style=" behavior: url(webservice.htc);"></div>

    and call the methods on the above div using:

    handle.useService(SERVICE_URL + "?WSDL", "MyFunction");)
  3. For Firefox:
  4. var oSoapCall = new SOAPCall()
  5. The universal approach where we make our own raw XML SOAP request and send this request, collect the response, and parse it like raw XML. Somewhat like this:
  6. //create a soap request in xml
    var soapRequest = "<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"
                     + "<" + sMethod + "xmlns=\"" 
                     + SOAP_ACTION_BASE + "\">\n"
                     + "<op1>" + sOp1 + "</op1>\n"
                     + "<op2>" + sOp2 + "</op2>\n"
                     + "</" + sMethod + ">\n"
                     + "</soap:Body>\n"
                     + "</soap:Envelope>\n";
     //create a soap header
        var sSoapActionHeader = SOAP_ACTION_BASE + "/" + sMethod;
        crreat a request
      oXmlHttp.open("POST", SERVICE_URL, true);
      //when request is made, handle it appropriately
      oXmlHttp.onreadystatechange = function(){//call appropriate method};
      
      //set various headers for the request
      oXmlHttp.setRequestHeader("Content-Type", "text/xml");
      oXmlHttp.setRequestHeader("SOAPAction", sSoapActionHeader);
      //send the request
      oXmlHttp.send(sRequest);

Having said the above things, here's an example of how we can call the Web Service. This approach relates a little bit to the third approach above. However, for convenience, I have enabled HTTP communication for my Web Service here. This gives my Web Service the ability to communicate using HTTP POST and HTTP GET. For this, the following code should be added to the system.web section of the web.config:

<webServices>
  <protocols>
    <add name="HttpGet"/>
    <add name="HttpPost"/>
  </protocols>
</webServices>

The above step will enable GET and POST interaction with our Web Service class. This saves me the time to create an XML SOAP request like I created above and make the HTTP request instead of the SOAP request. Further, there are multiple workarounds and approaches for this as well. For a clue, please see the server-side article.

Using the Code

Once you do the above, fetching a response from the Web Service becomes very simple. Following is the code for fetching the response:

var xmlDoc;
var http =  new XMLHttpRequest();
var isFirefox = false;

function callGetLatestPoll()
{
    if(xmlDoc!=null)return;
    if (document.implementation && document.implementation.createDocument)
    {
        xmlDoc = document.implementation.createDocument("", "", null);
        xmlDoc.onload = fetchforfirefox;
    }
    else if (window.ActiveXObject)
    {
        xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
        xmlDoc.onreadystatechange = function () {
            if (xmlDoc.readyState == 4){isFirefox = false; fetchlatestpoll();}
        };
     }
    else
    {
        alert("Your browser do not support the script for polling service.");
        return;
    }
    xmlDoc.load("http://localhost/poll/PollService.asmx/GetLatestPoll");
}

function fetchlatestpoll()
{
    // code for reading and displaying data for internet explorer
    b1 = xmlDoc.documentElement;
    document.getElementById("txtId").innerText  = b1.childNodes.item(0).text;
    ..............
    .................
}

function fetchforfirefox()
{
    isFirefox=true;
    //code for reading and displaying data for firefox
    b1 = xmlDoc.childNodes.item("PollServiceBO");
    
    for(var temp1 = 0; temp1<b1.childNodes.length;temp1++)
    {
    if(b1.childNodes.item(temp1).childNodes.item(0)!=null)
    {
        var currentNode = b1.childNodes.item(temp1);
        switch(currentNode.nodeName)
        {
            case "ID":
              alert(currentNode.nodeName + " is Set");
              document.getElementById('txtId').innerHTML = 
                       currentNode.childNodes.item(0).nodeValue;
              break;
            .......
            .........
        }
    }

The above code is simple. My Web Service is PollService.asmx and my WebMethod is GetLatestPoll. It will return an object called PollServiceBO which looks like below:

<?xml version="1.0" encoding="utf-8" ?> 
- <PollServiceBO xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xmlns:xsd="http://www.w3.org/2001/XMLSchema" 
      xmlns="http://tempuri.org/">
  <ID>106</ID> 
  <Question>Test question1?</Question> 
  <option1>Test option1</option1> 
  <option2>Test option2</option2> 
  <option3>Test option3</option3> 
  <option4>Test option4.</option4> 
  <dateAdded>2008-07-17T16:39:04.49</dateAdded> 
  </PollServiceBO>

The real issue is how to post the data when a Web Service takes a parameter as input. Here is the code for it:

var xmlDoc;
var http =null;
var isFirefox = false;

function callPostMethod()
{
    var url = "http://localhost/poll/PollService.asmx/GetPollById";
    var params = "PollId=106";

    try
    {
        // Firefox, Opera 8.0+, Safari
        http =new XMLHttpRequest();
        isFirefox = true;
    }
    catch (e)
    {
        // Internet Explorer
        try
        {
            http =new ActiveXObject("Msxml2.XMLHTTP");
        }
        catch (e)
        {
            http =new ActiveXObject("Microsoft.XMLHTTP");
        }
    }

    http.open("POST", url, true);
    //Send the proper header information along with the request
    http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    http.setRequestHeader("Content-length", params.length);
    http.setRequestHeader("Connection", "close");
    http.onreadystatechange = function() {//Call a function when the state changes.
    if(http.readyState == 4 && http.status == 200) {
        xmlDoc = http.responseXML;
        if(isFirefox)
           {fetchforfirefox();}
        else
           {fetchlatestpoll();}
    }
}
http.send(params);
}

Yes, you got the point right! The above code calls the Web Service PollService.asmx's method GetPollById using HTTP POST ,method and the parameter passed to this service is PollId.

Note: For further discussion on the server-side aspects and source code, please view: HTML UI using Web Service.

License

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

About the Author

okdone

Web Developer

Singapore Singapore

Member
OK Noted. It'll be done. Smile | :)

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
Generalaccessing .net webservice using axis java client + (401)Unauthorized Pinmemberrama_amaru2:53 15 Jan '09  
GeneralRe: accessing .net webservice using axis java client + (401)Unauthorized [modified] PinmemberAmit Kumar Thakur16:19 11 Feb '09  
GeneralThere is some bug in the Browser when not IE!! [modified] PinmemberJLKEngine00820:25 16 Sep '08  
GeneralRe: There is some bug in the Browser when not IE!! PinmemberAmit Kumar Thakur1:35 9 Oct '08  
GeneralRe: There is some bug in the Browser when not IE!! PinmemberAmit Kumar Thakur17:56 11 May '09  
QuestionQuestion? PinmemberJLKEngine0080:42 13 Sep '08  
AnswerRe: Question? PinmemberAmit Kumar Thakur1:01 16 Sep '08  
Generalinteresting subject, poor man explanation Pinmemberedwardsoft14:00 1 Aug '08  
GeneralSource Code PinmemberDewey23:45 18 Jul '08  

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Mobile
Web02 | 2.5.120209.1 | Last Updated 16 Sep 2008
Article Copyright 2008 by okdone
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid