XMLHttp : Step 2

How to call Webserver methods using Javascript

 

If you are planning to call your own ASP.Net webservice from client side using XMLHttp you need to configure its web.config.

Add the following inside <system.web>:

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

Paste the following in your htm page. This, however, requires you to fine tune according to your setup. I am using the default namespaces for the XML SOAP header, and my webservice resides on one of my servers.

<html><head><script language="javascript">

//Instantiated an XMLHTTP object.

var xmlRequest = new ActiveXObject("MSXML2.XMLHTTP");

//The following is the event handler for the object.

function OnComplete(){var spn = document.getElementById("ContentSpan");

//object.readyState gives us the current status of the async operation. The meaning of status code is printed on the page using the innerHTML property of span. e.g. readyState value 1 corresponds to an open connection.

switch(xmlRequest.readyState){case 1:spn.innerHTML = "connection opened."break;case 2:spn.innerHTML += "<br>POST request sent."break;case 3:spn.innerHTML += "<br>recieving data...<br>"break;case 4:var responseXML = xmlRequest.responseText;spn.innerHTML += responseXML;alert("Length of response = " + responseXML.length); spn.innerHTML += "<br>complete."break;}}

//The following is actually the handling the onClick event for the button.

function Invoke_Click(){

//The following creates a SOAP header for the request.

var soapEnvelope = "<soap:Envelope xmlns:xsi=\"

https://www.w3.org/2001/XMLSchema-instance\""soapEnvelope += " xmlns:xsd=\"https://www.w3.org/2001/XMLSchema\""soapEnvelope += " xmlns:soap=\"https://schemas.xmlsoap.org/soap/envelope/\">"soapEnvelope += "<soap:Body>"soapEnvelope += " <About xmlns=\"https://tempuri.org/\" />"soapEnvelope += "</soap:Body>"soapEnvelope += "</soap:Envelope>"

//Assign OnComplete handler to onreadystatechanged. This handler asynchronously gives the status of the response.

xmlRequest.onreadystatechange = OnComplete;

//Open the connection, send a POST request to the Webservice. The "true" parameter marks that an async request is sent.

xmlRequest.open("POST", "

https://sanjeets-2k3/LogParserWS/LogParserService.asmx/HelloWorld", true);try{

//The Content-Type needs to be set to text/xml

xmlRequest.setRequestHeader("Content-Type", "text/xml");

//Use the send method to send the request. You can also add the request header that we created above. Although its optional.xmlRequest.send(soapEnvelope);}catch(e){alert(e.message);} }

</script>

</head><body>

//A simple HTML button.

<input type="button" id="InvokeButton" value="Invoke" onclick="Invoke_Click();" /><br />

//A span to write the response HTML.

<span id="ContentSpan"></span></body></html>

Comments

  1. Ajax basics - "Asynchronous JavaScript and XML," is a web development technique for creating interactive