SlideShare a Scribd company logo
AJAX & Web Services
Prepared By
Yogaraja C A
Ramco Institute of Technology
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)
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.
Architecture
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.
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.
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
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")
Create an XMLHttpRequest Object
 variable = new XMLHttpRequest();
 var xhttp = new XMLHttpRequest();
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:
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.
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();
}
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
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.
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
}
AJAX XML
<CATALOG>
<CD>
<TITLE>Empire Burlesque</TITLE>
<ARTIST>Bob Dylan</ARTIST>
<COUNTRY>USA</COUNTRY>
<PRICE>10.90</PRICE>
</CD>
<CD>
<TITLE>Hide your heart</TITLE>
<ARTIST>Bonnie Tyler</ARTIST>
<COUNTRY>UK</COUNTRY>
<PRICE>9.90</PRICE>
</CD>
<CATALOG>
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();
}
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;
}
AJAX PHP
function showHint(str) {
if (str.length == 0) {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("txtHint").innerHTML = this.responseT
ext;
}
};
xmlhttp.open("GET", "gethint.php?q=" + str, true);
xmlhttp.send();
}
}
<input type="text" onkeyup="showHint(this.value)">
AJAX PHP(gethint.php)
$a[] = "Wenche";
$a[] = "Vicky";
$q = $_REQUEST["q"];
$hint = "";
if ($q !== "") {
$q = strtolower($q);
$len=strlen($q);
foreach($a as $name) {
if (stristr($q, substr($name, 0, $len))) {
if ($hint === "") {
$hint = $name;
} else {
$hint .= ", $name";
}
}
}
}
echo $hint === "" ? "no suggestion" : $hint;
?>
Call Back Function(cb.html)
<html>
<head>
<script>
function showHint(str, url, cFunction) {
if (str.length == 0) {
document.getElementById("one").innerHTML = "Suggestions";
return;
} else {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
cFunction(this);
}
};
xmlhttp.open("GET", url.concat(str), true);
xmlhttp.send();
}
}
Call Back Function(cb.html)
function myFunction1(xhttp) {
document.getElementById("one").innerHTML = xhttp.responseText;
}
function myFunction2(xhttp) {
document.getElementById("two").innerHTML = xhttp.responseText;
}
</script>
</head>
<body>
<p><b>Start typing a name in the input field below:</b></p>
<form>
uid : <input type="text" onkeyup="showHint(this.value, 'uid.php?q=', myFunction1)"><span id="one"></span><br>
Pwd : <input type="text" onkeyup="showHint(this.value, 'pwd.php?q=', myFunction2)"><span id="two"></span>
</form>
</body>
</html>
Call Back Function(uid.php)
<?php
$a[]="Wenche";
$a[]="Vicky";
$q=$_REQUEST['q'];
$hint="";
if($q!="")
{
$q=strtolower($q);
$len=strlen($q);
foreach($a as $name)
{
if(stristr($q, substr($name,0,$len)))
{
if($hint=="")
{
$hint=$name;
}
else
{
$hint.=",$name";
}
}
}
}
if($hint=="")
{
echo "no suggestion";
}
else
{
echo $hint;
}
?>
Call Back Function(pwd.php)
<?php
$a[]=“pass1";
$a[]=“pass2";
$q=$_REQUEST['q'];
$hint="";
if($q!="")
{
$q=strtolower($q);
$len=strlen($q);
foreach($a as $name)
{
if(stristr($q, substr($name,0,$len)))
{
if($hint=="")
{
$hint=$name;
}
else
{
$hint.=",$name";
}
}
}
}
if($hint=="")
{
echo "no suggestion";
}
else
{
echo $hint;
}
?>
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.
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
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.
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.
Examples of Web services
 Apache Axis
 Apache Axis2
 Glassfish
 Semantic web service
 Apache CXF
 SoapUI
 LoadUI
 Fuse Services Framework
 Hessian
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.
Components of Web Service
 SOAP (Simple Object Access Protocol)
 WSDL (Web services description language)
 UDDI (Universal Description, Discovery, and Integration)
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.
SOAP
SOAP
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.
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.
WSDL
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.
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
WSDL
<definitions>
<message name="TutorialRequest">
<part name="TutorialID" type="xsd:string"/>
</message>
<message name="TutorialResponse">
<part name="TutorialName" type="xsd:string"/>
</message>
<portType name="Tutorial_PortType">
<operation name="Tutorial">
<input message="tns:TutorialRequest"/>
<output message="tns:TutorialResponse"/>
</operation>
</portType>
WSDL
<binding name="Tutorial_Binding" type="tns:Tutorial_PortType">
<soap:binding style="rpc"
transport="http://schemas.xmlsoap.org/soap/http"/>
<operation name="Tutorial">
<soap:operation soapAction="Tutorial"/>
<input>
</input>
<output>
</output>
</operation>
</binding>
</definitions>
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.
Web service Architecture
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.
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.
Web service Characteristics
 They are XML-Based
 Loosely Coupled
 Synchronous or Asynchronous functionality
 Ability to support Remote Procedure Calls (RPCs)
 Supports Document Exchange
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.
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.
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
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
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
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;
}
}
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.
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>
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>

More Related Content

What's hot

JavaScript - Chapter 12 - Document Object Model
  JavaScript - Chapter 12 - Document Object Model  JavaScript - Chapter 12 - Document Object Model
JavaScript - Chapter 12 - Document Object Model
WebStackAcademy
 
Python lambda functions with filter, map & reduce function
Python lambda functions with filter, map & reduce functionPython lambda functions with filter, map & reduce function
Python lambda functions with filter, map & reduce function
ARVIND PANDE
 
Sgml and xml
Sgml and xmlSgml and xml
Sgml and xml
Jaya Kumari
 
JavaScript Promises
JavaScript PromisesJavaScript Promises
JavaScript Promises
Derek Willian Stavis
 
REST Easy with Django-Rest-Framework
REST Easy with Django-Rest-FrameworkREST Easy with Django-Rest-Framework
REST Easy with Django-Rest-Framework
Marcel Chastain
 
Webservices
WebservicesWebservices
Webservices
Gerard Sylvester
 
Introduction to Web Services
Introduction to Web ServicesIntroduction to Web Services
Introduction to Web Services
Thanachart Numnonda
 
Python RESTful webservices with Python: Flask and Django solutions
Python RESTful webservices with Python: Flask and Django solutionsPython RESTful webservices with Python: Flask and Django solutions
Python RESTful webservices with Python: Flask and Django solutions
Solution4Future
 
String and string buffer
String and string bufferString and string buffer
String and string bufferkamal kotecha
 
Introduction to the Web API
Introduction to the Web APIIntroduction to the Web API
Introduction to the Web API
Brad Genereaux
 
Unit 3. Input and Output
Unit 3. Input and OutputUnit 3. Input and Output
Unit 3. Input and Output
Ashim Lamichhane
 
JDBC
JDBCJDBC
Python programming introduction
Python programming introductionPython programming introduction
Python programming introduction
Siddique Ibrahim
 
Java Web Services [1/5]: Introduction to Web Services
Java Web Services [1/5]: Introduction to Web ServicesJava Web Services [1/5]: Introduction to Web Services
Java Web Services [1/5]: Introduction to Web Services
IMC Institute
 
Asp.net server controls
Asp.net server controlsAsp.net server controls
Asp.net server controlsRaed Aldahdooh
 
Battle Of The Microservice Frameworks: Micronaut versus Quarkus edition!
Battle Of The Microservice Frameworks: Micronaut versus Quarkus edition! Battle Of The Microservice Frameworks: Micronaut versus Quarkus edition!
Battle Of The Microservice Frameworks: Micronaut versus Quarkus edition!
Michel Schudel
 
Refactoring, 2nd Edition
Refactoring, 2nd EditionRefactoring, 2nd Edition
Refactoring, 2nd Edition
jexp
 

What's hot (20)

JavaScript - Chapter 12 - Document Object Model
  JavaScript - Chapter 12 - Document Object Model  JavaScript - Chapter 12 - Document Object Model
JavaScript - Chapter 12 - Document Object Model
 
Python lambda functions with filter, map & reduce function
Python lambda functions with filter, map & reduce functionPython lambda functions with filter, map & reduce function
Python lambda functions with filter, map & reduce function
 
Sgml and xml
Sgml and xmlSgml and xml
Sgml and xml
 
JavaScript Promises
JavaScript PromisesJavaScript Promises
JavaScript Promises
 
REST Easy with Django-Rest-Framework
REST Easy with Django-Rest-FrameworkREST Easy with Django-Rest-Framework
REST Easy with Django-Rest-Framework
 
Webservices
WebservicesWebservices
Webservices
 
Introduction to Web Services
Introduction to Web ServicesIntroduction to Web Services
Introduction to Web Services
 
ASP.NET Web form
ASP.NET Web formASP.NET Web form
ASP.NET Web form
 
Python cgi programming
Python cgi programmingPython cgi programming
Python cgi programming
 
Python RESTful webservices with Python: Flask and Django solutions
Python RESTful webservices with Python: Flask and Django solutionsPython RESTful webservices with Python: Flask and Django solutions
Python RESTful webservices with Python: Flask and Django solutions
 
String and string buffer
String and string bufferString and string buffer
String and string buffer
 
Introduction to the Web API
Introduction to the Web APIIntroduction to the Web API
Introduction to the Web API
 
Unit 3. Input and Output
Unit 3. Input and OutputUnit 3. Input and Output
Unit 3. Input and Output
 
JDBC
JDBCJDBC
JDBC
 
Python programming introduction
Python programming introductionPython programming introduction
Python programming introduction
 
Java Web Services [1/5]: Introduction to Web Services
Java Web Services [1/5]: Introduction to Web ServicesJava Web Services [1/5]: Introduction to Web Services
Java Web Services [1/5]: Introduction to Web Services
 
Asp.net server controls
Asp.net server controlsAsp.net server controls
Asp.net server controls
 
Soap vs rest
Soap vs restSoap vs rest
Soap vs rest
 
Battle Of The Microservice Frameworks: Micronaut versus Quarkus edition!
Battle Of The Microservice Frameworks: Micronaut versus Quarkus edition! Battle Of The Microservice Frameworks: Micronaut versus Quarkus edition!
Battle Of The Microservice Frameworks: Micronaut versus Quarkus edition!
 
Refactoring, 2nd Edition
Refactoring, 2nd EditionRefactoring, 2nd Edition
Refactoring, 2nd Edition
 

Similar to Ajax

Unit-5.pptx
Unit-5.pptxUnit-5.pptx
Unit-5.pptx
itzkuu01
 
AJAX
AJAXAJAX
AJAX
AJAXAJAX
Asynchronous JavaScript & XML (AJAX)
Asynchronous JavaScript & XML (AJAX)Asynchronous JavaScript & XML (AJAX)
Asynchronous JavaScript & XML (AJAX)
Adnan Sohail
 
Core Java tutorial at Unit Nexus
Core Java tutorial at Unit NexusCore Java tutorial at Unit Nexus
Core Java tutorial at Unit Nexus
Unit Nexus Pvt. Ltd.
 
Introduction to Ajax programming
Introduction to Ajax programmingIntroduction to Ajax programming
Introduction to Ajax programming
Fulvio Corno
 
Lec 7
Lec 7Lec 7
Ajax and xml
Ajax and xmlAjax and xml
Ajax and xml
sawsan slii
 
Ajax
AjaxAjax
jQuery - Chapter 5 - Ajax
jQuery - Chapter 5 -  AjaxjQuery - Chapter 5 -  Ajax
jQuery - Chapter 5 - Ajax
WebStackAcademy
 
Ajax Lecture Notes
Ajax Lecture NotesAjax Lecture Notes
Ajax Lecture Notes
Santhiya Grace
 
Implementing AJAX in PHP. Asynchronous JavaScript and XML
Implementing AJAX in PHP. Asynchronous JavaScript and XMLImplementing AJAX in PHP. Asynchronous JavaScript and XML
Implementing AJAX in PHP. Asynchronous JavaScript and XML
SanthiNivas
 
Ajax
AjaxAjax
Ajax Introduction
Ajax IntroductionAjax Introduction
Ajax Introduction
Oliver Cai
 
AJAX.pptx
AJAX.pptxAJAX.pptx
AJAX.pptx
ssuser0a07a1
 

Similar to Ajax (20)

Unit-5.pptx
Unit-5.pptxUnit-5.pptx
Unit-5.pptx
 
AJAX
AJAXAJAX
AJAX
 
AJAX
AJAXAJAX
AJAX
 
Asynchronous JavaScript & XML (AJAX)
Asynchronous JavaScript & XML (AJAX)Asynchronous JavaScript & XML (AJAX)
Asynchronous JavaScript & XML (AJAX)
 
Core Java tutorial at Unit Nexus
Core Java tutorial at Unit NexusCore Java tutorial at Unit Nexus
Core Java tutorial at Unit Nexus
 
Introduction to Ajax programming
Introduction to Ajax programmingIntroduction to Ajax programming
Introduction to Ajax programming
 
Ajax
AjaxAjax
Ajax
 
Lec 7
Lec 7Lec 7
Lec 7
 
Servlets intro
Servlets introServlets intro
Servlets intro
 
Copy of ajax tutorial
Copy of ajax tutorialCopy of ajax tutorial
Copy of ajax tutorial
 
Ajax and xml
Ajax and xmlAjax and xml
Ajax and xml
 
Ajax
AjaxAjax
Ajax
 
jQuery - Chapter 5 - Ajax
jQuery - Chapter 5 -  AjaxjQuery - Chapter 5 -  Ajax
jQuery - Chapter 5 - Ajax
 
Ajax
AjaxAjax
Ajax
 
Ajax Lecture Notes
Ajax Lecture NotesAjax Lecture Notes
Ajax Lecture Notes
 
Ajax Tuturial
Ajax TuturialAjax Tuturial
Ajax Tuturial
 
Implementing AJAX in PHP. Asynchronous JavaScript and XML
Implementing AJAX in PHP. Asynchronous JavaScript and XMLImplementing AJAX in PHP. Asynchronous JavaScript and XML
Implementing AJAX in PHP. Asynchronous JavaScript and XML
 
Ajax
AjaxAjax
Ajax
 
Ajax Introduction
Ajax IntroductionAjax Introduction
Ajax Introduction
 
AJAX.pptx
AJAX.pptxAJAX.pptx
AJAX.pptx
 

More from Yoga Raja

Php
PhpPhp
Xml
XmlXml
Database connect
Database connectDatabase connect
Database connect
Yoga Raja
 
Java Servlet
Java ServletJava Servlet
Java Servlet
Yoga Raja
 
JSP- JAVA SERVER PAGES
JSP- JAVA SERVER PAGESJSP- JAVA SERVER PAGES
JSP- JAVA SERVER PAGES
Yoga Raja
 
JSON
JSONJSON
JSON
Yoga Raja
 
Java script
Java scriptJava script
Java script
Yoga Raja
 
Think-Pair-Share
Think-Pair-ShareThink-Pair-Share
Think-Pair-Share
Yoga Raja
 
Minute paper
Minute paperMinute paper
Minute paper
Yoga Raja
 
Decision support system-MIS
Decision support system-MISDecision support system-MIS
Decision support system-MIS
Yoga Raja
 

More from Yoga Raja (10)

Php
PhpPhp
Php
 
Xml
XmlXml
Xml
 
Database connect
Database connectDatabase connect
Database connect
 
Java Servlet
Java ServletJava Servlet
Java Servlet
 
JSP- JAVA SERVER PAGES
JSP- JAVA SERVER PAGESJSP- JAVA SERVER PAGES
JSP- JAVA SERVER PAGES
 
JSON
JSONJSON
JSON
 
Java script
Java scriptJava script
Java script
 
Think-Pair-Share
Think-Pair-ShareThink-Pair-Share
Think-Pair-Share
 
Minute paper
Minute paperMinute paper
Minute paper
 
Decision support system-MIS
Decision support system-MISDecision support system-MIS
Decision support system-MIS
 

Recently uploaded

6th International Conference on Machine Learning & Applications (CMLA 2024)
6th International Conference on Machine Learning & Applications (CMLA 2024)6th International Conference on Machine Learning & Applications (CMLA 2024)
6th International Conference on Machine Learning & Applications (CMLA 2024)
ClaraZara1
 
digital fundamental by Thomas L.floydl.pdf
digital fundamental by Thomas L.floydl.pdfdigital fundamental by Thomas L.floydl.pdf
digital fundamental by Thomas L.floydl.pdf
drwaing
 
Understanding Inductive Bias in Machine Learning
Understanding Inductive Bias in Machine LearningUnderstanding Inductive Bias in Machine Learning
Understanding Inductive Bias in Machine Learning
SUTEJAS
 
bank management system in java and mysql report1.pdf
bank management system in java and mysql report1.pdfbank management system in java and mysql report1.pdf
bank management system in java and mysql report1.pdf
Divyam548318
 
一比一原版(UC Berkeley毕业证)加利福尼亚大学|伯克利分校毕业证成绩单专业办理
一比一原版(UC Berkeley毕业证)加利福尼亚大学|伯克利分校毕业证成绩单专业办理一比一原版(UC Berkeley毕业证)加利福尼亚大学|伯克利分校毕业证成绩单专业办理
一比一原版(UC Berkeley毕业证)加利福尼亚大学|伯克利分校毕业证成绩单专业办理
skuxot
 
ACRP 4-09 Risk Assessment Method to Support Modification of Airfield Separat...
ACRP 4-09 Risk Assessment Method to Support Modification of Airfield Separat...ACRP 4-09 Risk Assessment Method to Support Modification of Airfield Separat...
ACRP 4-09 Risk Assessment Method to Support Modification of Airfield Separat...
Mukeshwaran Balu
 
Harnessing WebAssembly for Real-time Stateless Streaming Pipelines
Harnessing WebAssembly for Real-time Stateless Streaming PipelinesHarnessing WebAssembly for Real-time Stateless Streaming Pipelines
Harnessing WebAssembly for Real-time Stateless Streaming Pipelines
Christina Lin
 
Recycled Concrete Aggregate in Construction Part III
Recycled Concrete Aggregate in Construction Part IIIRecycled Concrete Aggregate in Construction Part III
Recycled Concrete Aggregate in Construction Part III
Aditya Rajan Patra
 
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
obonagu
 
14 Template Contractual Notice - EOT Application
14 Template Contractual Notice - EOT Application14 Template Contractual Notice - EOT Application
14 Template Contractual Notice - EOT Application
SyedAbiiAzazi1
 
CHINA’S GEO-ECONOMIC OUTREACH IN CENTRAL ASIAN COUNTRIES AND FUTURE PROSPECT
CHINA’S GEO-ECONOMIC OUTREACH IN CENTRAL ASIAN COUNTRIES AND FUTURE PROSPECTCHINA’S GEO-ECONOMIC OUTREACH IN CENTRAL ASIAN COUNTRIES AND FUTURE PROSPECT
CHINA’S GEO-ECONOMIC OUTREACH IN CENTRAL ASIAN COUNTRIES AND FUTURE PROSPECT
jpsjournal1
 
sieving analysis and results interpretation
sieving analysis and results interpretationsieving analysis and results interpretation
sieving analysis and results interpretation
ssuser36d3051
 
New techniques for characterising damage in rock slopes.pdf
New techniques for characterising damage in rock slopes.pdfNew techniques for characterising damage in rock slopes.pdf
New techniques for characterising damage in rock slopes.pdf
wisnuprabawa3
 
Low power architecture of logic gates using adiabatic techniques
Low power architecture of logic gates using adiabatic techniquesLow power architecture of logic gates using adiabatic techniques
Low power architecture of logic gates using adiabatic techniques
nooriasukmaningtyas
 
Exception Handling notes in java exception
Exception Handling notes in java exceptionException Handling notes in java exception
Exception Handling notes in java exception
Ratnakar Mikkili
 
Advanced control scheme of doubly fed induction generator for wind turbine us...
Advanced control scheme of doubly fed induction generator for wind turbine us...Advanced control scheme of doubly fed induction generator for wind turbine us...
Advanced control scheme of doubly fed induction generator for wind turbine us...
IJECEIAES
 
PROJECT FORMAT FOR EVS AMITY UNIVERSITY GWALIOR.ppt
PROJECT FORMAT FOR EVS AMITY UNIVERSITY GWALIOR.pptPROJECT FORMAT FOR EVS AMITY UNIVERSITY GWALIOR.ppt
PROJECT FORMAT FOR EVS AMITY UNIVERSITY GWALIOR.ppt
bhadouriyakaku
 
A review on techniques and modelling methodologies used for checking electrom...
A review on techniques and modelling methodologies used for checking electrom...A review on techniques and modelling methodologies used for checking electrom...
A review on techniques and modelling methodologies used for checking electrom...
nooriasukmaningtyas
 
Technical Drawings introduction to drawing of prisms
Technical Drawings introduction to drawing of prismsTechnical Drawings introduction to drawing of prisms
Technical Drawings introduction to drawing of prisms
heavyhaig
 
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
thanhdowork
 

Recently uploaded (20)

6th International Conference on Machine Learning & Applications (CMLA 2024)
6th International Conference on Machine Learning & Applications (CMLA 2024)6th International Conference on Machine Learning & Applications (CMLA 2024)
6th International Conference on Machine Learning & Applications (CMLA 2024)
 
digital fundamental by Thomas L.floydl.pdf
digital fundamental by Thomas L.floydl.pdfdigital fundamental by Thomas L.floydl.pdf
digital fundamental by Thomas L.floydl.pdf
 
Understanding Inductive Bias in Machine Learning
Understanding Inductive Bias in Machine LearningUnderstanding Inductive Bias in Machine Learning
Understanding Inductive Bias in Machine Learning
 
bank management system in java and mysql report1.pdf
bank management system in java and mysql report1.pdfbank management system in java and mysql report1.pdf
bank management system in java and mysql report1.pdf
 
一比一原版(UC Berkeley毕业证)加利福尼亚大学|伯克利分校毕业证成绩单专业办理
一比一原版(UC Berkeley毕业证)加利福尼亚大学|伯克利分校毕业证成绩单专业办理一比一原版(UC Berkeley毕业证)加利福尼亚大学|伯克利分校毕业证成绩单专业办理
一比一原版(UC Berkeley毕业证)加利福尼亚大学|伯克利分校毕业证成绩单专业办理
 
ACRP 4-09 Risk Assessment Method to Support Modification of Airfield Separat...
ACRP 4-09 Risk Assessment Method to Support Modification of Airfield Separat...ACRP 4-09 Risk Assessment Method to Support Modification of Airfield Separat...
ACRP 4-09 Risk Assessment Method to Support Modification of Airfield Separat...
 
Harnessing WebAssembly for Real-time Stateless Streaming Pipelines
Harnessing WebAssembly for Real-time Stateless Streaming PipelinesHarnessing WebAssembly for Real-time Stateless Streaming Pipelines
Harnessing WebAssembly for Real-time Stateless Streaming Pipelines
 
Recycled Concrete Aggregate in Construction Part III
Recycled Concrete Aggregate in Construction Part IIIRecycled Concrete Aggregate in Construction Part III
Recycled Concrete Aggregate in Construction Part III
 
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
 
14 Template Contractual Notice - EOT Application
14 Template Contractual Notice - EOT Application14 Template Contractual Notice - EOT Application
14 Template Contractual Notice - EOT Application
 
CHINA’S GEO-ECONOMIC OUTREACH IN CENTRAL ASIAN COUNTRIES AND FUTURE PROSPECT
CHINA’S GEO-ECONOMIC OUTREACH IN CENTRAL ASIAN COUNTRIES AND FUTURE PROSPECTCHINA’S GEO-ECONOMIC OUTREACH IN CENTRAL ASIAN COUNTRIES AND FUTURE PROSPECT
CHINA’S GEO-ECONOMIC OUTREACH IN CENTRAL ASIAN COUNTRIES AND FUTURE PROSPECT
 
sieving analysis and results interpretation
sieving analysis and results interpretationsieving analysis and results interpretation
sieving analysis and results interpretation
 
New techniques for characterising damage in rock slopes.pdf
New techniques for characterising damage in rock slopes.pdfNew techniques for characterising damage in rock slopes.pdf
New techniques for characterising damage in rock slopes.pdf
 
Low power architecture of logic gates using adiabatic techniques
Low power architecture of logic gates using adiabatic techniquesLow power architecture of logic gates using adiabatic techniques
Low power architecture of logic gates using adiabatic techniques
 
Exception Handling notes in java exception
Exception Handling notes in java exceptionException Handling notes in java exception
Exception Handling notes in java exception
 
Advanced control scheme of doubly fed induction generator for wind turbine us...
Advanced control scheme of doubly fed induction generator for wind turbine us...Advanced control scheme of doubly fed induction generator for wind turbine us...
Advanced control scheme of doubly fed induction generator for wind turbine us...
 
PROJECT FORMAT FOR EVS AMITY UNIVERSITY GWALIOR.ppt
PROJECT FORMAT FOR EVS AMITY UNIVERSITY GWALIOR.pptPROJECT FORMAT FOR EVS AMITY UNIVERSITY GWALIOR.ppt
PROJECT FORMAT FOR EVS AMITY UNIVERSITY GWALIOR.ppt
 
A review on techniques and modelling methodologies used for checking electrom...
A review on techniques and modelling methodologies used for checking electrom...A review on techniques and modelling methodologies used for checking electrom...
A review on techniques and modelling methodologies used for checking electrom...
 
Technical Drawings introduction to drawing of prisms
Technical Drawings introduction to drawing of prismsTechnical Drawings introduction to drawing of prisms
Technical Drawings introduction to drawing of prisms
 
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
 

Ajax

  • 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 }
  • 16. AJAX XML <CATALOG> <CD> <TITLE>Empire Burlesque</TITLE> <ARTIST>Bob Dylan</ARTIST> <COUNTRY>USA</COUNTRY> <PRICE>10.90</PRICE> </CD> <CD> <TITLE>Hide your heart</TITLE> <ARTIST>Bonnie Tyler</ARTIST> <COUNTRY>UK</COUNTRY> <PRICE>9.90</PRICE> </CD> <CATALOG>
  • 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; }
  • 19. AJAX PHP function showHint(str) { if (str.length == 0) { document.getElementById("txtHint").innerHTML = ""; return; } else { var xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { document.getElementById("txtHint").innerHTML = this.responseT ext; } }; xmlhttp.open("GET", "gethint.php?q=" + str, true); xmlhttp.send(); } } <input type="text" onkeyup="showHint(this.value)">
  • 20. AJAX PHP(gethint.php) $a[] = "Wenche"; $a[] = "Vicky"; $q = $_REQUEST["q"]; $hint = ""; if ($q !== "") { $q = strtolower($q); $len=strlen($q); foreach($a as $name) { if (stristr($q, substr($name, 0, $len))) { if ($hint === "") { $hint = $name; } else { $hint .= ", $name"; } } } } echo $hint === "" ? "no suggestion" : $hint; ?>
  • 21. Call Back Function(cb.html) <html> <head> <script> function showHint(str, url, cFunction) { if (str.length == 0) { document.getElementById("one").innerHTML = "Suggestions"; return; } else { var xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { cFunction(this); } }; xmlhttp.open("GET", url.concat(str), true); xmlhttp.send(); } }
  • 22. Call Back Function(cb.html) function myFunction1(xhttp) { document.getElementById("one").innerHTML = xhttp.responseText; } function myFunction2(xhttp) { document.getElementById("two").innerHTML = xhttp.responseText; } </script> </head> <body> <p><b>Start typing a name in the input field below:</b></p> <form> uid : <input type="text" onkeyup="showHint(this.value, 'uid.php?q=', myFunction1)"><span id="one"></span><br> Pwd : <input type="text" onkeyup="showHint(this.value, 'pwd.php?q=', myFunction2)"><span id="two"></span> </form> </body> </html>
  • 23. Call Back Function(uid.php) <?php $a[]="Wenche"; $a[]="Vicky"; $q=$_REQUEST['q']; $hint=""; if($q!="") { $q=strtolower($q); $len=strlen($q); foreach($a as $name) { if(stristr($q, substr($name,0,$len))) { if($hint=="") { $hint=$name; } else { $hint.=",$name"; } } } } if($hint=="") { echo "no suggestion"; } else { echo $hint; } ?>
  • 24. Call Back Function(pwd.php) <?php $a[]=“pass1"; $a[]=“pass2"; $q=$_REQUEST['q']; $hint=""; if($q!="") { $q=strtolower($q); $len=strlen($q); foreach($a as $name) { if(stristr($q, substr($name,0,$len))) { if($hint=="") { $hint=$name; } else { $hint.=",$name"; } } } } if($hint=="") { echo "no suggestion"; } else { echo $hint; } ?>
  • 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.
  • 33. SOAP
  • 34. SOAP
  • 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.
  • 37. WSDL
  • 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
  • 40. WSDL <definitions> <message name="TutorialRequest"> <part name="TutorialID" type="xsd:string"/> </message> <message name="TutorialResponse"> <part name="TutorialName" type="xsd:string"/> </message> <portType name="Tutorial_PortType"> <operation name="Tutorial"> <input message="tns:TutorialRequest"/> <output message="tns:TutorialResponse"/> </operation> </portType>
  • 41. WSDL <binding name="Tutorial_Binding" type="tns:Tutorial_PortType"> <soap:binding style="rpc" transport="http://schemas.xmlsoap.org/soap/http"/> <operation name="Tutorial"> <soap:operation soapAction="Tutorial"/> <input> </input> <output> </output> </operation> </binding> </definitions>
  • 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>