1. AJAX & Web Services
Prepared By
Yogaraja C A
Ramco Institute of Technology
2. Introduction
AJAX is an acronym for Asynchronous
JavaScript and XML.
It is a group of inter-related technologies like
javascript, dom, xml, html, css etc.
AJAX is not a programming language.
AJAX just uses a combination of:
A browser built-in XMLHttpRequest object
(to request data from a web server)
JavaScript and HTML DOM (to display or use
the data)
3. Introduction
AJAX applications might use XML to transport
data, but it is equally common to transport
data as plain text or JSON text.
AJAX allows web pages to be updated
asynchronously by exchanging data with a web
server behind the scenes.
This means that it is possible to update parts of
a web page, without reloading the whole page.
5. Architecture
1. User sends a request from the UI and a
javascript call goes to XMLHttpRequest object.
2. HTTP Request is sent to the server by
XMLHttpRequest object.
3. Server interacts with the database using JSP,
PHP, Servlet, ASP.net etc.
4. Data is retrieved.
5. Server sends XML data or JSON data to the
XMLHttpRequest callback function.
6. HTML and CSS data is displayed on the
browser.
6. AJAX - The XMLHttpRequest Object
All modern browsers support the
XMLHttpRequest object.
The XMLHttpRequest object can be used to
exchange data with a server behind the
scenes. This means that it is possible to
update parts of a web page, without reloading
the whole page.
7. XMLHttpRequest Object Methods
Method Description
new XMLHttpRequest() Creates a new XMLHttpRequest object
abort() Cancels the current request
getAllResponseHeaders() Returns header information
getResponseHeader() Returns specific header information
open(method,url,async,user,psw) Specifies the request
method: the request type GET or POST
url: the file location
async: true (asynchronous) or false (synchronous)
user: optional user name
psw: optional password
send() Sends the request to the server
Used for GET requests
send(string) Sends the request to the server.
Used for POST requests
setRequestHeader() Adds a label/value pair to the header to be sent
8. XMLHttpRequest Object Properties
Property Description
onreadystatechange Defines a function to be called when the readyState property
changes
readyState Holds the status of the XMLHttpRequest.
0: request not initialized
1: server connection established
2: request received
3: processing request
4: request finished and response is ready
responseText Returns the response data as a string
responseXML Returns the response data as XML data
status Returns the status-number of a request
200: "OK"
403: "Forbidden"
404: "Not Found"
statusText Returns the status-text (e.g. "OK" or "Not Found")
9. Create an XMLHttpRequest Object
variable = new XMLHttpRequest();
var xhttp = new XMLHttpRequest();
10. Send a Request To a Server
To send a request to a server, we use the
open() and send() methods of the
XMLHttpRequest object:
xhttp.open("GET", "ajax_info.txt", true);
xhttp.send();
Asynchronous - True or False?
Server requests should be sent asynchronously.
The async parameter of the open() method should be set to true:
11. Server Response
The onreadystatechange Property
The readyState property holds the status of
the XMLHttpRequest.
The onreadystatechange property defines a
function to be executed when the readyState
changes.
The status property and the statusText
property holds the status of the
XMLHttpRequest object.
12. Server Response
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML =
this.responseText;
}
};
xhttp.open("GET", "ajax_info.txt", true);
xhttp.send();
}
13. Server Response Properties & Methods
Property Description
responseText get the response data as a string
responseXML get the response data as XML data
Method Description
getResponseHeader() Returns specific header information from the server resource
getAllResponseHeaders() Returns all the header information from the server resource
14. Using a Callback Function
A callback function is a function passed as a parameter to
another function.
If you have more than one AJAX task in a website, you
should create one function for executing the
XMLHttpRequest object, and one callback function for
each AJAX task.
The function call should contain the URL and what
function to call when the response is ready.
15. Using a Callback Function
loadDoc("url-1", myFunction1);
loadDoc("url-2", myFunction2);
function loadDoc(url, cFunction) {
var xhttp;
xhttp=new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
cFunction(this);
}
};
xhttp.open("GET", url, true);
xhttp.send();
}
function myFunction1(xhttp) {
// action goes here
}
function myFunction2(xhttp) {
// action goes here
}
17. AJAX XML
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
myFunction(this);
}
};
xhttp.open("GET", "cd_catalog.xml", true);
xhttp.send();
}
18. AJAX XML
function myFunction(xml) {
var i;
var xmlDoc = xml.responseXML;
var table="<tr><th>Title</th><th>Artist</th></tr>";
var x = xmlDoc.getElementsByTagName("CD");
for (i = 0; i <x.length; i++) {
table += "<tr><td>" +
x[i].getElementsByTagName("TITLE")[0].childNodes[0].nodeVa
lue +
"</td><td>" +
x[i].getElementsByTagName("ARTIST")[0].childNodes[0].nodeV
alue +
"</td></tr>";
}
document.getElementById("demo").innerHTML = table;
}
25. WEB SERVICES
Web service is a standardized medium to propagate
communication between the client and server
applications on the World Wide Web.
A web service is a software module which is designed to
perform a certain set of tasks.
The web services can be searched for over the network
and can also be invoked accordingly.
When invoked, the web service would be able to provide
functionality to the client which invokes that web
service.
26. WEB SERVICES
Web services are application components
Web services communicate using open protocols
Web services are self-contained and self-describing
Web services can be discovered using UDDI
Web services can be used by other applications
HTTP and XML is the basis for Web services
27. WEB SERVICES
These requests are made through what is known as remote procedure calls.
Remote Procedure Calls(RPC) are calls made to methods which are hosted
by the relevant web service.
28. Advantages of Web Services
Exposing Business Functionality on the network - A web
service is a unit of managed code that provides some sort of
functionality to client applications or end users.
Interoperability amongst applications - Web services allow
various applications to talk to each other and share data and
services among themselves.
A Standardized Protocol which everybody understands - Web
services use standardized industry protocol for the
communication.
Reduction in cost of communication - Web services use SOAP
over HTTP protocol, so you can use your existing low-cost
internet for implementing web services.
29. Examples of Web services
Apache Axis
Apache Axis2
Glassfish
Semantic web service
Apache CXF
SoapUI
LoadUI
Fuse Services Framework
Hessian
30. Type of Web Service
SOAP web services.
RESTful web services.
In order for a web service to be fully functional, there are
certain components that need to be in place.
These components need to be present irrespective of
whatever development language is used for programming
the web service.
31. Components of Web Service
SOAP (Simple Object Access Protocol)
WSDL (Web services description language)
UDDI (Universal Description, Discovery, and Integration)
32. SOAP
SOAP is known as a transport-independent messaging
protocol.
SOAP is based on transferring XML data as SOAP
Messages.
Only the structure of the XML document follows a
specific pattern, but not the content.
The best part of Web services and SOAP is that its all
sent via HTTP, which is the standard web protocol.
35. SOAP
Each SOAP document needs to have a root element known as
the <Envelope> element. The root element is the first
element in an XML document.
The "envelope" is in turn divided into 2 parts. The first is the
header, and the next is the body.
The header contains the routing data which is basically the
information which tells the XML document to which client it
needs to be sent to.
The body element is the main element which contains the
definition of the web methods along with any parameter
information if required.
The body will contain the actual message.
36. WSDL
A web service cannot be used if it cannot be found.
The client invoking the web service should know where
the web service actually resides.
The WSDL file is again an XML-based file which basically
tells the client application what the web service does.
By using the WSDL document, the client application
would be able to understand where the web service is
located and how it can be utilized.
38. WSDL
<types> - tag is used to define all the complex datatypes,
which will be used in the message exchanged between the
client application and the web service.
<message> - The message parameter in the WSDL definition
is used to define the different data elements for each
operation performed by the web service.
<portType> - This actually describes the operation which can
be performed by the web service.
This operation can take 2 messages; one is an input message,
and the other is the output message.
<binding> - This element contains the protocol which is used.
<service> - tag is a name given to the web service itself.
39. WSDL
Element Description
<types> Defines the (XML Schema) data types used by the web
service
<message> Defines the data elements for each operation
<portType> Describes the operations that can be performed and the
messages involved.
<binding> Defines the protocol and data format for each port type
42. UDDI
UDDI is a standard for describing, publishing, and discovering the
web services that are provided by a particular service provider.
It provides a specification which helps in hosting the information
on web services.
how can a client application locate a WSDL file to understand the
various operations offered by a web service?
So UDDI is the answer to this and provides a repository on which
WSDL files can be hosted.
So the client application will have complete access to the UDDI,
which acts as a database containing all the WSDL files.
44. Web service Architecture
Provider - The provider creates the web service and makes it
available to client application who want to use it.
Requestor - A requestor is nothing but the client application that
needs to contact a web service. The client application can be a
.Net, Java, or any other language based application which looks
for some sort of functionality via a web service.
Broker - The broker is nothing but the application which provides
access to the UDDI. The UDDI, as discussed in the earlier topic
enables the client application to locate the web service.
45. Web service Architecture
Publish - A provider informs the broker (service registry) about
the existence of the web service by using the broker's publish
interface to make the service accessible to clients.
Find - The requestor consults the broker to locate a published
web service
Bind - With the information it gained from the broker(service
registry) about the web service, the requestor is able to bind, or
invoke, the web service.
46. Web service Characteristics
They are XML-Based
Loosely Coupled
Synchronous or Asynchronous functionality
Ability to support Remote Procedure Calls (RPCs)
Supports Document Exchange
47. RESTFUL Web service
REST stands for REpresentational State Transfer. REST is used to
build web services that are lightweight, maintainable, and
scalable in nature.
More and more applications are moving to the Restful
architecture. This is because there are a lot of people now using
mobile devices and a wider variety of applications moving to the
cloud.
The main aspects of REST are the resources which reside on the
server and the verbs of GET, POST, PUT and DELETE, which can be
used to work with these resources.
48. RESTFUL Web service
Visual Studio and.Net can be used to create Restful web services.
When Testing web services for POST and PUT, you need to use
another tool called fiddler which can be used to send the POST
and PUT request to the server.
49. SOAP vs REST
SOAP REST
SOAP is a protocol. REST is an Architectural style in which a web service can
only be treated as a RESTful service
SOAP cannot make use of REST since SOAP is a protocol
and REST is an architectural pattern.
REST can make use of SOAP as the underlying protocol
for web services, because in the end it is just an
architectural pattern.
SOAP requires more bandwidth for its usage. REST does not need much bandwidth when requests are
sent to the server.
SOAP can only work with XML format. As seen from SOAP
messages, all data passed is in XML format.
REST permits different data format such as Plain text,
HTML, XML, JSON, etc. But the most preferred format
for transferring data is JSON.
When to use SOAP
• Asynchronous processing and subsequent invocation
• A Formal means of communication
• Stateful operations
When to use REST
• Limited resources and bandwidth
• Statelessness
• Caching
• Ease of coding
Challenges
• WSDL file
• Document size
Challenges
• Lack of Security
• Lack of state
50. creating web service that acts as service provider
File -> New Project -> Web Application
In that web application, create new web service by right click the project New Web Service.
New web service is added into the project.
In that New web service right click select add operation.
Set name of the operation and return type of the operation
Add essential parameters for that operation and exceptions.
Click ok
51. creating web service that acts as service provider
File -> New Project -> Web Application
In that web application, create new web service by right click the project New Web Service.
New web service is added into the project.
In that New web service right click select add operation.
Set name of the operation and return type of the operation
Add essential parameters for that operation and exceptions.
Click ok
Modifying the operation code, deploy the web application and test webservice
http://localhost:8080/WebApplication3/NewWebService?WSDL
52. creating web service that acts as service provider
Web Service
package pack;
import javax.jws.WebService;
import javax.jws.WebMethod;
import javax.jws.WebParam;
@WebService(serviceName = "AddService")
public class AddService {
@WebMethod(operationName = "add")
public int add(@WebParam(name = "a") int a, @WebParam(name = "b") int b) {
return a+b;
}
}
53. Consumer or requestor that gets web service
File -> New Project -> Web Application
In that application right click New Web ServiceClient
Choose webservice and click finish that automatically includes Generated Source( jas_ws) and Web
Service References
Creating new jsp file that includes web service by dragging webservice method ‘add’ from web
service reference and test it.
54. Consumer or requestor that gets web service
New.jsp
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<h1>Hello World!</h1> <%-- start web service invocation --%><hr/>
<b> Addition </b>
55. Consumer or requestor that gets web service
<%
try {
// creating service object
pack.Arith_Service service = new pack.Arith_Service();
// creating class object
pack.Arith port = service.getArithPort();
int num1 = 23;
int num2 = 28;
// invoking service method addition
int result = port.add(num1, num2);
out.println("Result (a+b) = "+result);
} catch (Exception ex) {
// TODO handle custom exceptions here
} %> </body></html>