Javascript SOAP Client

Javascript SOAP Client

Sometimes it is nice to get data using a SOAP call. However with using Javascript there are some disadvantages and hurdles that you may need to over come. As with any fun little project you will need some materials before we get started.

  1. Favorite Text Editor
  2. Browser
  3. Endpoint for the SOAP call – should be a url
  4. SOAP request string

If you have all these things ready to go, the next thing we need to make sure of is that the proper headers are set on the server side. If this is not your server that your are trying to hit then you will need to ask the administrator of the server if they can fix up the proper access.

The Headers we need are

Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: POST
Access-Control-Allow-Headers: SOAPAction, Content-Type

If you happen to have a PHP SOAP server you can add these lines to the top of your code. Please remember that the header functions will need to load before you start printing other text to the page.

header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: POST");
header("Access-Control-Allow-Headers: SOAPAction, Content-Type");

On the server side of things you can do a SOAP request with out all the Access Control headers. These are used as security precautions on the Browser side to prevent people from possible hacks. If you use this method to get data make sure that you properly analyze the security risks.

If all your headers are set properly then you are ready to make a SOAP call using Javascript. Copy the following code to your html file and view the alert in the browser with the return code. You can adjust the xml and url to fit your circumstances.

var xml = "YOUR-SOAP-REQUEST";
var url = "http://someurl.com/soap/";
var xmlhttp= new XMLHttpRequest();
xmlhttp.open("POST", url, true);
xmlhttp.onreadystatechange = function () {
 if (xmlhttp.readyState == 4) {
  alert(xmlhttp.responseText);
 }
};
xmlhttp.setRequestHeader("SOAPAction", "");
xmlhttp.setRequestHeader("Content-Type", "text/xml");
xmlhttp.send(xml);

Bonus Points : If you happen to use HTTP Auth on your web server, you can make the url look like the following and replace the username and password with your credentials

http://username:password@www.someurl.com/soap/