This blog post will show you how to invoke the SOAP-based ASP.NET web service method from JavaScript using XMLHttpRequest.Sometimes if you want to update a section of the page, then instead of loading the entire page, we make the asynchronous request.
using System;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class Service : System.Web.Services.WebService
{
public Service () {
//Uncomment the following line if using designed components
//InitializeComponent();
}
[WebMethod]
public string HelloWorld(string strName) {
return "Hello" +strName;
}
}
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Untitled Page</title>
<script type="text/javascript"> function sendDataAsXML_SOAP() {
var req_params = "", url = "", number = 0, type = "";
/* Configure Parameters */
url = "http://localhost/TestWebservice/Service.asmx";
user = document.getElementById("Text1").value;
req_params = "<?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 >";
req_params = req_params + "<strName>" + user + "</strName>";
req_params = req_params + "</HelloWorld></soap:Body></soap:Envelope>";
alert(req_params);
/* Send XML/SOAP Request To Web Service Using Browser's Javascript DOM */
try {
ajax_request = new XMLHttpRequest();
}
catch (trymicrosoft) {
try {
ajax_request = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (othermicrosoft) {
try {
ajax_request = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (failed) {
ajax_request = false;
}
}
}
ajax_request.open("POST", url, true);
ajax_request.setRequestHeader("Content-Type", "text/xml;charset=utf-8");
ajax_request.onreadystatechange = receiveXML_SOAPData;
ajax_request.send(req_params);
}
function receiveXML_SOAPData() {
if (ajax_request.readyState == 4) {
if (ajax_request.status == 200) {
/* Parse The Response Data */
//result.innerText = ajax_request.responseText;
alert(ajax_request.responseText);
}
}
}
</script>
</head>
<body>
<form action="#">
<input type="text" id="Text1" />
<input type="button" onclick="sendDataAsXML_SOAP();" value="Call WebService" />
</form>
</body>
</html>