Simplest SOAP example

What is the simplest SOAP example using Javascript?

To be as useful as possible, the answer should:

  • Be functional (in other words actually work)
  • Send at least one parameter that can be set elsewhere in the code
  • Process at least one result value that can be read elsewhere in the code
  • Work with most modern browser versions
  • Be as clear and as short as possible, without using an external library

This is the simplest JavaScript SOAP Client I can create.

    <title>SOAP JavaScript Client Test</title>
    <script type="text/javascript">
        function soap() {
            var xmlhttp = new XMLHttpRequest();
  'POST', '', true);

            // build SOAP request
            var sr =
                '<?xml version="1.0" encoding="utf-8"?>' +
                '<soapenv:Envelope ' + 
                    'xmlns:xsi="" ' +
                    'xmlns:api="" ' +
                    'xmlns:xsd="" ' +
                    'xmlns:soapenv="">' +
                    '<soapenv:Body>' +
                        '<api:some_api_call soapenv:encodingStyle="">' +
                            '<username xsi:type="xsd:string">login_username</username>' +
                            '<password xsi:type="xsd:string">password</password>' +
                        '</api:some_api_call>' +
                    '</soapenv:Body>' +

            xmlhttp.onreadystatechange = function () {
                if (xmlhttp.readyState == 4) {
                    if (xmlhttp.status == 200) {
                        // alert('done. use firebug/console to see network response');
            // Send the POST request
            xmlhttp.setRequestHeader('Content-Type', 'text/xml');
            // send request
            // ...
    <form name="Demo" action="" method="post">
            <input type="button" value="Soap" onclick="soap();" />
</html> <!-- typo -->

There are many quirks in the way browsers handle XMLHttpRequest, this JS code will work across all browsers:

This JS code converts XML into easy to use JavaScript objects:

The JS code above can be included in the page to meet your no external library requirement.

var symbol = "MSFT"; 
var xmlhttp = new XMLHttpRequest();"POST", "",true);
xmlhttp.onreadystatechange=function() {
 if (xmlhttp.readyState == 4) {
  // convert XML to JSON 
  var json = XMLObjectifier.xmlToJSON(xmlhttp.responseXML);
  var result = json.Body[0].GetQuoteResponse[0].GetQuoteResult[0].Text;
  // Result text is escaped XML string, convert string to XML object then convert to JSON object
  json = XMLObjectifier.xmlToJSON(XMLObjectifier.textToXML(result));
  alert(symbol + ' Stock Quote: $' + json.Stock[0].Last[0].Text); 
xmlhttp.setRequestHeader("SOAPAction", "http://www.webserviceX.NET/GetQuote");
xmlhttp.setRequestHeader("Content-Type", "text/xml");
var xml = '<?xml version="1.0" encoding="utf-8"?>' +
 '<soap:Envelope xmlns:xsi="" ' +
                'xmlns:xsd="" ' +
                'xmlns:soap="">' + 
   '<soap:Body> ' +
     '<GetQuote xmlns="http://www.webserviceX.NET/"> ' +
       '<symbol>' + symbol + '</symbol> ' +
     '</GetQuote> ' +
   '</soap:Body> ' +
// ...Include Google and Terracoder JS code here...

Two other options:

This cannot be done with straight JavaScript unless the web service is on the same domain as your page. Edit: In 2008 and in IE<10 this cannot be done with straight javascript unless the service is on the same domain as your page.

If the web service is on another domain [and you have to support IE<10] then you will have to use a proxy page on your own domain that will retrieve the results and return them to you. If you do not need old IE support then you need to add CORS support to your service. In either case, you should use something like the lib that timyates suggested because you do not want to have to parse the results yourself.

If the web service is on your own domain then don't use SOAP. There is no good reason to do so. If the web service is on your own domain then modify it so that it can return JSON and save yourself the trouble of dealing with all the hassles that come with SOAP.

Short answer is: Don't make SOAP requests from javascript. Use a web service to request data from another domain, and if you do that then parse the results on the server-side and return them in a js friendly form.

You can use the jquery.soap plugin to do the work for you.

This script uses $.ajax to send a SOAPEnvelope. It can take XML DOM, XML string or JSON as input and the response can be returned as either XML DOM, XML string or JSON too.

Example usage from the site:

    url: '',
    method: 'helloWorld',

    data: {
        name: 'Remy Blom',
        msg: 'Hi!'

    success: function (soapResponse) {
        // do stuff with soapResponse
        // if you want to have the response as JSON use soapResponse.toJSON();
        // or soapResponse.toString() to get XML string
        // or soapResponse.toXML() to get XML DOM
    error: function (SOAPResponse) {
        // show error


JSON is preferred for front end use because it is javascript. Therefore you have no XML to deal with. SOAP is a pain without using a library because of this. Somebody mentioned SOAPClient, which is a good library, we started with it for our project. However it had some limitations and we had to rewrite large chunks of it. It's been released as SOAPjs and supports passing complex objects to the server, and includes some sample proxy code to consume services from other domains.

Has anyone tried this?

Seems very easy to implement.


url: '',
method: 'helloWorld',

data: {
    name: 'Remy Blom',
    msg: 'Hi!'

success: function (soapResponse) {
    // do stuff with soapResponse
    // if you want to have the response as JSON use soapResponse.toJSON();
    // or soapResponse.toString() to get XML string
    // or soapResponse.toXML() to get XML DOM
error: function (SOAPResponse) {
    // show error

will result in

        <name>Remy Blom</name>

    <title>Calling Web Service from jQuery</title>
    <script type="text/javascript" src=""></script>
    <script type="text/javascript">
        $(document).ready(function () {
            $("#btnCallWebService").click(function (event) {
                var wsUrl = "";
                var soapRequest ='<soap:Envelope xmlns:xsi="" xmlns:xsd="" xmlns:soap="">   <soap:Body> <getQuote xmlns:impl="">  <symbol>' + $("#txtName").val() + '</symbol>   </getQuote> </soap:Body></soap:Envelope>';
                    type: "POST",
                    url: wsUrl,
                    contentType: "text/xml",
                    dataType: "xml",
                    data: soapRequest,
                    success: processSuccess,
                    error: processError


        function processSuccess(data, status, req) { alert('success');
            if (status == "success")


        function processError(data, status, req) {
            //alert(req.responseText + " " + status);

        Calling Web Services with jQuery/AJAX
    Enter your name:
    <input id="txtName" type="text" />
    <input id="btnCallWebService" value="Call web service" type="button" />
    <div id="response" ></div>

Hear is best JavaScript with SOAP tutorial with example.

Some great examples (and a ready-made JavaScript SOAP client!) here:

Check the readme, and beware the same-origin browser restriction.

Easily consume SOAP Web services with JavaScript -> Listing B

function fncAddTwoIntegers(a, b)
    varoXmlHttp = new XMLHttpRequest();"POST",
    oXmlHttp.setRequestHeader("Content-Type", "text/xml");
    oXmlHttp.setRequestHeader("SOAPAction", "");
    oXmlHttp.send(" \
<soap:Envelope xmlns:xsi='' \
xmlns:xsd='' \
 xmlns:soap=''> \
  <soap:Body> \
    <AddTwoIntegers xmlns=''> \
      <IntegerOne>" + a + "</IntegerOne> \
      <IntegerTwo>" + b + "</IntegerTwo> \
    </AddTwoIntegers> \
  </soap:Body> \
</soap:Envelope> \
    return oXmlHttp.responseXML.selectSingleNode("//AddTwoIntegersResult").text;

This may not meet all your requirements but it is a start at actually answering your question. (I switched XMLHttpRequest() for ActiveXObject("MSXML2.XMLHTTP")).

Simplest example would consist of:

  1. Getting user input.
  2. Composing XML SOAP message similar to this

    <soap:Envelope xmlns:xsi=""
        <GetInfoByZIP xmlns="http://www.webserviceX.NET">
  3. POSTing message to webservice url using XHR

  4. Parsing webservice's XML SOAP response similar to this

    <soap:Envelope xmlns:soap=""
      <GetInfoByZIPResponse xmlns="http://www.webserviceX.NET">
        <NewDataSet xmlns="">
  5. Presenting results to user.

But it's a lot of hassle without external JavaScript libraries.

function SoapQuery(){
  var namespace = "";
  var site = "";
  var xmlhttp = new ActiveXObject("Msxml2.ServerXMLHTTP.6.0");
  xmlhttp.setOption(2,  13056 );  /* if use standard proxy */
  var args,fname =  arguments.callee.caller.toString().match(/ ([^\(]+)/)[1]; /*??? ????????? ?-???*/
  try { args =   arguments.callee.caller.arguments.callee.toString().match(/\(([^\)]+)/)[1].split(",");  
    } catch (e) { args = Array();};'POST',site,true);  
  var i, ret = "", q = '<?xml version="1.0" encoding="utf-8"?>'+
   '<soap:Envelope xmlns:xsi="" xmlns:xsd="" xmlns:soap="">'+
   '<soap:Body><'+fname+ ' xmlns="'+namespace+'">';
  for (i=0;i<args.length;i++) q += "<" + args[i] + ">" + arguments.callee.caller.arguments[i] +  "</" + args[i] + ">";
  q +=   '</'+fname+'></soap:Body></soap:Envelope>';
            // Send the POST request
            xmlhttp.setRequestHeader("SOAPAction",namespace + fname);
            xmlhttp.setRequestHeader('Content-Type', 'text/xml');
            //WScript.Echo("?????? XML:" + q);
     if  (xmlhttp.waitForResponse(5000)) ret = xmlhttp.responseText;
    return ret;

function GetForm(prefix,post_vars){return SoapQuery();};
function SendOrder2(guid,order,fio,phone,mail){return SoapQuery();};

function SendOrder(guid,post_vars){return SoapQuery();};

Angularjs $http wrap base on XMLHttpRequest. As long as at the header content set following code will do.

"Content-Type": "text/xml; charset=utf-8"

For example:

function callSoap(){
var url = "";
var soapXml = "<soapenv:Envelope xmlns:soapenv=\"\" xmlns:web=\"http://www.webserviceX.NET/\"> "+
         "<soapenv:Header/> "+
         "<soapenv:Body> "+
         "<web:GetQuote> "+
         "<web:symbol></web:symbol> "+
         "</web:GetQuote> "+
         "</soapenv:Body> "+
         "</soapenv:Envelope> ";

    return $http({
          url: url,  
          method: "POST",  
          data: soapXml,  
          headers: {  
              "Content-Type": "text/xml; charset=utf-8"
         return message;

    function callSoapComplete(data, status, headers, config) {
        // Convert to JSON Ojbect from xml
        // var x2js = new X2JS();
        // var str2json = x2js.xml_str2json(;
        // return str2json;



The question is 'What is the simplest SOAP example using Javascript?'

This answer is of an example in the Node.js environment, rather than a browser. (Let's name the script soap-node.js) And we will use the public SOAP web service from Europe PMC as an example to get the reference list of an article.

const XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
const DOMParser = require('xmldom').DOMParser;

function parseXml(text) {
    let parser = new DOMParser();
    let xmlDoc = parser.parseFromString(text, "text/xml");
    Array.from(xmlDoc.getElementsByTagName("reference")).forEach(function (item) {
        console.log('Title: ', item.childNodes[3].childNodes[0].nodeValue);


function soapRequest(url, payload) {
    let xmlhttp = new XMLHttpRequest();'POST', url, true);

    // build SOAP request
    xmlhttp.onreadystatechange = function () {
        if (xmlhttp.readyState == 4) {
            if (xmlhttp.status == 200) {

    // Send the POST request
    xmlhttp.setRequestHeader('Content-Type', 'text/xml');

    `<?xml version="1.0" encoding="UTF-8"?>
    <S:Envelope xmlns:S="">
    <S:Header />
        <ns4:getReferences xmlns:ns4=""
            <email>[email protected]</email>

Before running the code, you need to install two packages:

npm install xmlhttprequest
npm install xmldom

Now you can run the code:

node soap-node.js

And you'll see the output as below:

Title:  Perspective: Sustaining the big-data ecosystem.
Title:  Making proteomics data accessible and reusable: current state of proteomics databases and repositories.
Title:  ProteomeXchange provides globally coordinated proteomics data submission and dissemination.
Title:  Toward effective software solutions for big biology.
Title:  The NIH Big Data to Knowledge (BD2K) initiative.
Title:  Database resources of the National Center for Biotechnology Information.
Title:  Europe PMC: a full-text literature database for the life sciences and platform for innovation.
Title:  Bio-ontologies-fast and furious.
Title:  BioPortal: ontologies and integrated data resources at the click of a mouse.
Title:  PubMed related articles: a probabilistic topic-based model for content similarity.
Title:  High-Impact Articles-Citations, Downloads, and Altmetric Score.