This tutorial is intended to guide you through the process of using SOAP (Simple Object Access Protocol) services in hybrid apps. By the end of this tutorial, you will be able to make calls to SOAP web services and handle XML responses using JavaScript.
A basic understanding of:
SOAP is a messaging protocol that allows programs running on disparate operating systems such as Windows and Linux to communicate with each other. It uses XML for its message format, which is platform-independent. SOAP can be used over HTTP/HTTPS, making it accessible from anywhere.
You make calls to SOAP services using AJAX. AJAX stands for Asynchronous JavaScript and XML. It's a set of web development techniques used to create asynchronous web applications. With AJAX, you can send and receive data from a server asynchronously without interfering with the display and behavior of the existing page.
The response from a SOAP service is typically an XML document. You can handle this response using the DOM Parser in JavaScript.
Below is a simple SOAP request using AJAX:
var xmlhttp = new XMLHttpRequest();
xmlhttp.open('POST', 'http://www.example.com/soap-endpoint.asmx?wsdl', true);
// build SOAP request
var sr =
'<?xml version="1.0" encoding="utf-8"?>' +
'<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> ' +
'<HelloWorld xmlns="http://tempuri.org/" />' +
'</soap:Body> ' +
'</soap:Envelope>';
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4) {
if (xmlhttp.status == 200) {
alert(xmlhttp.responseText);
}
}
}
xmlhttp.setRequestHeader('Content-Type', 'text/xml');
xmlhttp.send(sr);
This code initiates a SOAP request to a web service endpoint. It constructs a SOAP envelope with a HelloWorld
request, and sends the request. When the response is received, it alerts the response text.
In this tutorial, we've covered how to use SOAP services in hybrid apps. We've learned how to make calls to SOAP services and handle XML responses using JavaScript.
To continue learning, you can:
Solution:
if (xmlhttp.status == 200) {
var parser = new DOMParser();
var xmlDoc = parser.parseFromString(xmlhttp.responseText,"text/xml");
var message = xmlDoc.getElementsByTagName("Message")[0].childNodes[0].nodeValue;
document.getElementById("message").innerHTML = message;
}
In this code, we're using the DOMParser to parse the XML response. We then get the Message
element from the XML, and set its value in an HTML element with the id message
.
xmlhttp.onerror = function() {
alert('An error occurred during the transaction');
};
This code adds an error handler to the AJAX request. If an error occurs during the transaction, it alerts a message.