Friday, April 10, 2009

Call SOAP based web services through JavaScript

I had the task of calling a web service through code written in PHP with Smarty templates. For those interested "


Although Smarty is known as a "Template Engine", it would be more accurately described as a "Template/Presentation Framework." That is, it provides the programmer and template designer with a wealth of tools to automate tasks commonly dealt with at the presentation layer of an application. I stress the word Framework because Smarty is not a simple tag-replacing template engine. Although it can be used for such a simple purpose, its focus is on quick and painless development and deployment of your application, while maintaining high-performance, scalability, security and future growth. "


JavaScript: The Definitive Guide (Paperback) by David Flanagan has some great code in the section 21.7 XML and Web Services. You can basically use XMLHttpRequest object and XPath queries to make a simple SOAP request to a web service. I really did not want to get too much into details of how to configure PHP to call a Java web service and hence this relly helped me. You can use JavaScript code to contruct an XML document representing a SOAP request and uses XMLHttpRequest to send it to a web service. The code then uses an XPath query to extract the result from the SOAP response returned by the server.


I am using a simple SOAP request and SOAP response without any attempt to explain the protocol or the XML format. I am using Spring Web service on the server side and I do not use WSDL etc here. The server URL, method, and parameter name are all hardcoded into the sample code.


Using client-side JavaScript is severely constrained by the same-origin security policy. All browsers restrict the call if the web service resides on a different host(server). This means that JavaScript code for accessing a web service is typically useful only if it is hosted on the same server as the web service itself. To overcome this you can use Apache redirects on the machine where the html code resides to forward a url to the external machine.


In order to run the Example in IE, you can relax the same-origin security policy. Select Tools Internet Options Security and then click on the Internet tab in the resulting dialog. Scroll through the list of security options to find one named Access data sources across domains. This option is usually (and should be) set to disabled. In order to run this example, change it to prompt.



To allow this Example to run in Firefox, the example includes a call to the Firefox specific enablePrivilege() method. This call prompts the user to grant enhanced privileges to the script so that it can override the same-origin policy.


Parsing JavaScript is described in detail out here: http://www.hiteshagrawal.com/javascript/javascript-parsing-xml-in-javascript


HTML file


JavaScript file

No comments:

Post a Comment

Thank you for your feedback