Books related to this content
JavaScript SOAP Client Examples

How to setup a basic SOAP request using JavaScript?

This example clearly demonstrates a basic SOAP request to a web service that returns a Zip code information.
In this example I used one of the free web services provided by http://www.webservicex.net.
No WSDL verification, no local web service, just real out of life example - fast and simple.

Proxy file: "proxy.aspx"

SOAP Request:
<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>
   <GetInfoByZIP xmlns="http://www.webserviceX.NET">
    <USZip>string</USZip>
   </GetInfoByZIP>
  </soap:Body>
</soap:Envelope>

SOAP Response:
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
 <soap:Body>
  <GetInfoByZIPResponse xmlns="http://www.webserviceX.NET">
   <GetInfoByZIPResult>
    <NewDataSet xmlns="">
<Table>
  <CITY>...</CITY>
  <STATE>...</STATE>
  <ZIP>...</ZIP>
  <AREA_CODE>...</AREA_CODE>
  <TIME_ZONE>...</TIME_ZONE>
</Table>
    </NewDataSet>
   </GetInfoByZIPResult>
  </GetInfoByZIPResponse>
 </soap:Body>
</soap:Envelope>



JavaScript:

<script language="javascript" src="jquery.js"></script>
<script language="javascript" src="jqXMLUtils.js"></script>

<script language="javascript" src="jqSOAPClient.js"></script>

//You can use chained method that looks like this:
var soapBody = new SOAPObject("GetInfoByZIP");
soapBody.ns = "http://www.webserviceX.NET";
soapBody.appendChild(new SOAPObject("USZip")).val($("#txtZipCode").val());
//Here I set the value of the zip code

//Create a new SOAP Request pass SOAPAction and Body content parameters
var sr = new SOAPRequest("http://www.webserviceX.NET/GetInfoByZIP", soapBody);

//Lets send it
SOAPClient.Proxy = "proxy.aspx"; //Specify local proxy file
SOAPClient.SOAPServer = "http://www.webservicex.net/uszip.asmx"; //My proxy uses SOAPServer header to redirect my requests
SOAPClient.SendRequest(sr, processResponse); //Send request to server and assign callback function

function processResponse(respObj) {
 try {

//Notice how I set references to the returned values. SOAP Response node names are kept the same, and become arrays
  var responseMessage = respObj.Body[0].GetInfoByZIPResponse[0].GetInfoByZIPResult[0].NewDataSet[0].Table[0];
  //Let's set those textbox values (using jQuery)
  $("#txtCity").val(responseMessage.CITY[0].Text);
  $("#txtState").val(responseMessage.STATE[0].Text);
  $("#txtZip").val(responseMessage.ZIP[0].Text);
  $("#txtAreaCode").val(responseMessage.AREA_CODE[0].Text);
  $("#txtTimeZone").val(responseMessage.TIME_ZONE[0].Text);

 } catch(e) { alert("Unable to resolve ZIP Code"); }
}


Warning: Web Service may take a while to respond

How to write a SOAP Proxy?

My ASP.Net skills are not as good as my JavaScript skills, so feel free to modify your own versions of proxy file as you see fit.
Source code can also be downloaded here (use "Save As" option).
Warning: Just a word of advice, write an additional validation logic for your proxy to work only with requests sent from your domain / pages, otherwise some malicious user may hijack your proxy and relay through it unwanted traffic.

<%@ Page Language="VB" ContentType="text/html" ResponseEncoding="utf-8" validateRequest="false" %>
<%@ Import Namespace="System.Net" %>
<%@ Import Namespace="System.IO" %>

<%
'Set Response ContentType to "text/xml" or AJAX Request will fail to return responseXML value
Response.ContentType = "text/xml"
'Read SOAP Data sent by my SOAPClient JavaScript
Dim xmlInput = Request.BinaryRead(Request.TotalBytes)
Dim memStr as new MemoryStream(CType(xmlInput, Byte()))
Dim inputReader as new StreamReader(memStr)
Dim data = inputReader.ReadToEnd()
inputReader.Close()


'Read SOAPAction sent by my SOAPClient JavaScript
Dim soapAction as String = Request.ServerVariables("HTTP_SOAPAction") 'i.e. "http://www.webserviceX.NET/GetInfoByZIP"
'Read SOAPServer URL sent by my SOAPClient JavaScript
Dim soapServer as String = Request.ServerVariables("HTTP_SOAPServer") 'i.e. "http://www.webservicex.net/uszip.asmx"

'Create System.Net.WebRequest to make a request to a remote server
Dim objRequest As WebRequest = WebRequest.Create(soapServer)

'Set Header
objRequest.Method = "POST"
objRequest.ContentLength = data.Length
objRequest.ContentType = "text/xml"
objRequest.Headers.Add("SOAPAction", soapAction)


Try
Dim streamRequest As StreamWriter = New StreamWriter(objRequest.GetRequestStream())


'Write SOAP data to the request stream.
streamRequest.Write(data)
streamRequest.Close()


'Get Response Stream
Dim streamResponse As Stream = objRequest.GetResponse().GetResponseStream()
Dim streamRead As New StreamReader(streamResponse)


'Read response into a variable
Dim out = streamRead.ReadToEnd()

'Close the Stream Object.

streamResponse.Close()
streamRead.Close()


'Write response out

Response.Write(out)
Catch e As Exception
End Try
%>

PHP Version of proxy file has been developed and donated by Rodolphe Linais. Myself and all other PHP developpers would like to thank him for this great contribution. All support questions regarding this work please forward to Rodolphe at rodolphelinais-contact@yahoo.fr.
PHP Source code can be downloaded here.

<?php

// PHP Proxy


//put the HEADER data in the header

$this_header = getallheaders();
if ($this_header) {
$header = array();
foreach($this_header as $key => $value)
{
$header[] = $key.":".$value;
}
}

// URL of the SOAP server

$url = $this_header['SOAPServer'];

//Start the Curl session
$session = curl_init($url);

//Capture all data posted
$postdata = $HTTP_RAW_POST_DATA;

// Don't return HTTP headers. Do return the contents of the call
curl_setopt($session, CURLOPT_HEADER, false);
curl_setopt($session, CURLOPT_HTTPHEADER, $header);


// If it's a POST, put the POST data in the body
if ($postdata) {
curl_setopt ($session, CURLOPT_POSTFIELDS, $postdata);
}

// The web service returns XML. Set the Content-Type appropriately
header("Content-Type:text/xml");

// Make the call
$response = curl_exec($session);
$header_size = curl_getinfo($session,CURLINFO_HEADER_SIZE);
$result = substr($response, $header_size );


echo $result;

curl_close($session);

?>
Terracoder.com © 2007 | All Rights reserved
xmlObjectifier by terracoder.com is licensed under a Creative Commons Attribution-No Derivative Works 3.0 United States License. Based on a work at terracoder.com.

This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses.
Creative Commons License
Job Opportunities