![]() |
Web Development »
Web Services »
General
Beginner
License: The Code Project Open License (CPOL)
Calling A Web Service From HTML Page using AJAX and HTTP Post (for all browsers)By Amit Kumar ThakurCalling A Web Service From HTML Page using AJAX and HTTP Post (for all browsers) |
Javascript, XML, CSS, HTML, .NET (.NET 2.0), ASP.NET, Ajax, Dev, Design
|
||||||||||
|
Advanced Search Add to IE Search |
|
|
|
||||||||||||||||
This article introduces how we can call a Web Service using simple JavaScript and AJAX. This article discusses the client side aspect. For server side aspect and source code please visit this link
We can consume a web service from html page using:
//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 how we can call the web service. This approach relates a little bit to the 3rd 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 - following code should be added to the system.web section of web.config:
<webServices> <protocols> <add name="HttpGet"/> <add name="HttpPost"/> </protocols> </webServices>
Above step will enable GET and POST interaction with our web service class.
This saves me the time to create a xml soap like I created above and make HTTP request instead of SOAP request. Further, there are multiple workarounds and approaches for this as well. For one clue, please see the server side article.
Once you do the above thing, fetching a response from 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;
.......
.........
}
}
Above thing is simple. My WebService 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 thing is how we post the data when a web service takes a parameter as input. So 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 webservice PollService.asmx method GetPollById using HTTP post method and the parameter passed to this service is PollId.
Note: For further discussion on server side aspects and source code please view: HTML UI using Web Service..
| You must Sign In to use this message board. | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
General
News
Question
Answer
Joke
Rant
Admin
|
PermaLink |
Privacy |
Terms of Use
Last Updated: 15 Sep 2008 Editor: Sean Ewington |
Copyright 2008 by Amit Kumar Thakur Everything else Copyright © CodeProject, 1999-2009 Web22 | Advertise on the Code Project |