A Nostalgic Look at Using XMLHttpRequest with SOAP

It has been a long time since I did any work with the XmlHttpRequest object directly. Most of my XML geekery is done using .NET on the server side with web services, and ASP.NET AJAX 1.0 eliminated my need to directly touch XmlHttpRequest from JavaScript. However, today I found myself with a need to revisit the old-school way of calling a web service from JavaScript. For those interested in a little nostalgia, here's the code that I conjured up.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="https://www.w3.org/1999/xhtml" >

<head>

<title>Calling a Web Service Using XmlHttpRequest</title>

<script type="text/javascript" language="javascript">

var xmlhttp;

 

function on_click()

{

var xmlToSend = "<?xml version='1.0' encoding='utf-8'?>";

xmlToSend += "<soap:Envelope xmlns:xsi='https://www.w3.org/2001/XMLSchema-instance' ";

xmlToSend += "xmlns:xsd='https://www.w3.org/2001/XMLSchema' ";

xmlToSend += "xmlns:soap='https://schemas.xmlsoap.org/soap/envelope/'>";

xmlToSend += "<soap:Body><HelloWorld xmlns='https://tempuri.org/' />";

xmlToSend += "</soap:Body></soap:Envelope>";

 

var xmldoc = new ActiveXObject("Microsoft.XMLDOM");

xmldoc.loadXML(xmlToSend);

 

xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");

xmlhttp.onreadystatechange = state_Change;

xmlhttp.open("POST", "https://intranet.litwareinc.com/xdomain/WebService.asmx", false);

xmlhttp.setRequestHeader ("SOAPAction", "https://tempuri.org/HelloWorld");

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

xmlhttp.send(xmldoc);

 

var objResponse = document.getElementById("responseDiv");

objResponse.innerText = xmlhttp.responseXML.xml;

}

 

function state_Change()

{

// if xmlhttp shows "loaded"

if (xmlhttp.readyState==4)

{

// if "OK"

if (xmlhttp.status==200)

{

alert("OK");

}

else

{

alert("Problem retrieving XML data");

}

}

}

</script>

</head>

<body>

<div>

<h1>Click the button to call the web service</h1>

<input type="button" onclick="return on_click();" value="OK"/>

</div>

<div id="responseDiv">

 

</div>

</body>

</html>

 

The web service being called is a very simple ASMX web service, it is the default web service that you get when you click "Add New Item / Web Service" in Visual Studio with the HelloWorld WebMethod. Of course, this approach would work with any SOAP envelope, just make sure to set the request header so that ASMX knows how to dispatch to the proper endpoint handler.

The funny thing is comparing this example to how ASP.NET AJAX 1.0 makes it simple to call a web service. Good to have this bit of nostalgia posted here for reference, lest we forget how hard things used to be.

Resources: