SlideShare ist ein Scribd-Unternehmen 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>

Weitere ähnliche Inhalte

Was ist angesagt?

ASP.NET Web API and HTTP Fundamentals
ASP.NET Web API and HTTP FundamentalsASP.NET Web API and HTTP Fundamentals
ASP.NET Web API and HTTP Fundamentals
Ido Flatow
 
A python web service
A python web serviceA python web service
A python web service
Temian Vlad
 
Introduction to APIs
Introduction to APIsIntroduction to APIs
Introduction to APIs
Camille Baldock
 
Third party libraries and OSGi - a complicated relationship
Third party libraries and OSGi - a complicated relationshipThird party libraries and OSGi - a complicated relationship
Third party libraries and OSGi - a complicated relationship
Sascha Brinkmann
 
Rest api with Python
Rest api with PythonRest api with Python
Rest api with Python
Santosh Ghimire
 
C# web api
C# web apiC# web api
C# web api
Simplilearn
 
Fondamentaux d’une API REST
Fondamentaux d’une API RESTFondamentaux d’une API REST
Fondamentaux d’une API REST
Abdoulaye Dieng
 
Introduction to the Web API
Introduction to the Web APIIntroduction to the Web API
Introduction to the Web API
Brad Genereaux
 
OData Services
OData ServicesOData Services
OData Services
Jovan Popovic
 
Web Services PHP Tutorial
Web Services PHP TutorialWeb Services PHP Tutorial
Web Services PHP Tutorial
Lorna Mitchell
 
Python Built-in Functions and Use cases
Python Built-in Functions and Use casesPython Built-in Functions and Use cases
Python Built-in Functions and Use cases
Srajan Mor
 
Python libraries
Python librariesPython libraries
Python libraries
Prof. Dr. K. Adisesha
 
Qu'est ce qu'une api en 2019 ?
Qu'est ce qu'une api en 2019 ? Qu'est ce qu'une api en 2019 ?
Qu'est ce qu'une api en 2019 ?
Cellenza
 
HTTP and Your Angry Dog
HTTP and Your Angry DogHTTP and Your Angry Dog
HTTP and Your Angry Dog
Ross Tuck
 
REST API Design & Development
REST API Design & DevelopmentREST API Design & Development
REST API Design & Development
Ashok Pundit
 
Capstone turbine corporation e-finity distributed generation
Capstone turbine corporation  e-finity distributed generation Capstone turbine corporation  e-finity distributed generation
Capstone turbine corporation e-finity distributed generation
TNenergy
 
Web technologies: HTTP
Web technologies: HTTPWeb technologies: HTTP
Web technologies: HTTP
Piero Fraternali
 
Scala : programmation fonctionnelle
Scala : programmation fonctionnelleScala : programmation fonctionnelle
Scala : programmation fonctionnelle
MICHRAFY MUSTAFA
 
Google Cheat Sheet
Google Cheat SheetGoogle Cheat Sheet
Google Cheat Sheet
guest47b8f5d
 
ребусы одежда
ребусы одеждаребусы одежда
ребусы одежда
Irina1727
 

Was ist angesagt? (20)

ASP.NET Web API and HTTP Fundamentals
ASP.NET Web API and HTTP FundamentalsASP.NET Web API and HTTP Fundamentals
ASP.NET Web API and HTTP Fundamentals
 
A python web service
A python web serviceA python web service
A python web service
 
Introduction to APIs
Introduction to APIsIntroduction to APIs
Introduction to APIs
 
Third party libraries and OSGi - a complicated relationship
Third party libraries and OSGi - a complicated relationshipThird party libraries and OSGi - a complicated relationship
Third party libraries and OSGi - a complicated relationship
 
Rest api with Python
Rest api with PythonRest api with Python
Rest api with Python
 
C# web api
C# web apiC# web api
C# web api
 
Fondamentaux d’une API REST
Fondamentaux d’une API RESTFondamentaux d’une API REST
Fondamentaux d’une API REST
 
Introduction to the Web API
Introduction to the Web APIIntroduction to the Web API
Introduction to the Web API
 
OData Services
OData ServicesOData Services
OData Services
 
Web Services PHP Tutorial
Web Services PHP TutorialWeb Services PHP Tutorial
Web Services PHP Tutorial
 
Python Built-in Functions and Use cases
Python Built-in Functions and Use casesPython Built-in Functions and Use cases
Python Built-in Functions and Use cases
 
Python libraries
Python librariesPython libraries
Python libraries
 
Qu'est ce qu'une api en 2019 ?
Qu'est ce qu'une api en 2019 ? Qu'est ce qu'une api en 2019 ?
Qu'est ce qu'une api en 2019 ?
 
HTTP and Your Angry Dog
HTTP and Your Angry DogHTTP and Your Angry Dog
HTTP and Your Angry Dog
 
REST API Design & Development
REST API Design & DevelopmentREST API Design & Development
REST API Design & Development
 
Capstone turbine corporation e-finity distributed generation
Capstone turbine corporation  e-finity distributed generation Capstone turbine corporation  e-finity distributed generation
Capstone turbine corporation e-finity distributed generation
 
Web technologies: HTTP
Web technologies: HTTPWeb technologies: HTTP
Web technologies: HTTP
 
Scala : programmation fonctionnelle
Scala : programmation fonctionnelleScala : programmation fonctionnelle
Scala : programmation fonctionnelle
 
Google Cheat Sheet
Google Cheat SheetGoogle Cheat Sheet
Google Cheat Sheet
 
ребусы одежда
ребусы одеждаребусы одежда
ребусы одежда
 

Ähnlich wie 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
 
Ajax
AjaxAjax
Lec 7
Lec 7Lec 7
Servlets intro
Servlets introServlets intro
Servlets intro
vantinhkhuc
 
Copy of ajax tutorial
Copy of ajax tutorialCopy of ajax tutorial
Copy of ajax tutorial
Abhishek Kesharwani
 
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
AjaxAjax
Ajax Lecture Notes
Ajax Lecture NotesAjax Lecture Notes
Ajax Lecture Notes
Santhiya Grace
 
Ajax Tuturial
Ajax TuturialAjax Tuturial
Ajax Tuturial
Anup Singh
 
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
 

Ähnlich wie 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
 

Mehr von 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
 

Mehr von 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
 

Kürzlich hochgeladen

Casting-Defect-inSlab continuous casting.pdf
Casting-Defect-inSlab continuous casting.pdfCasting-Defect-inSlab continuous casting.pdf
Casting-Defect-inSlab continuous casting.pdf
zubairahmad848137
 
22CYT12-Unit-V-E Waste and its Management.ppt
22CYT12-Unit-V-E Waste and its Management.ppt22CYT12-Unit-V-E Waste and its Management.ppt
22CYT12-Unit-V-E Waste and its Management.ppt
KrishnaveniKrishnara1
 
学校原版美国波士顿大学毕业证学历学位证书原版一模一样
学校原版美国波士顿大学毕业证学历学位证书原版一模一样学校原版美国波士顿大学毕业证学历学位证书原版一模一样
学校原版美国波士顿大学毕业证学历学位证书原版一模一样
171ticu
 
spirit beverages ppt without graphics.pptx
spirit beverages ppt without graphics.pptxspirit beverages ppt without graphics.pptx
spirit beverages ppt without graphics.pptx
Madan Karki
 
KuberTENes Birthday Bash Guadalajara - K8sGPT first impressions
KuberTENes Birthday Bash Guadalajara - K8sGPT first impressionsKuberTENes Birthday Bash Guadalajara - K8sGPT first impressions
KuberTENes Birthday Bash Guadalajara - K8sGPT first impressions
Victor Morales
 
Transformers design and coooling methods
Transformers design and coooling methodsTransformers design and coooling methods
Transformers design and coooling methods
Roger Rozario
 
john krisinger-the science and history of the alcoholic beverage.pptx
john krisinger-the science and history of the alcoholic beverage.pptxjohn krisinger-the science and history of the alcoholic beverage.pptx
john krisinger-the science and history of the alcoholic beverage.pptx
Madan Karki
 
Curve Fitting in Numerical Methods Regression
Curve Fitting in Numerical Methods RegressionCurve Fitting in Numerical Methods Regression
Curve Fitting in Numerical Methods Regression
Nada Hikmah
 
Engineering Drawings Lecture Detail Drawings 2014.pdf
Engineering Drawings Lecture Detail Drawings 2014.pdfEngineering Drawings Lecture Detail Drawings 2014.pdf
Engineering Drawings Lecture Detail Drawings 2014.pdf
abbyasa1014
 
Embedded machine learning-based road conditions and driving behavior monitoring
Embedded machine learning-based road conditions and driving behavior monitoringEmbedded machine learning-based road conditions and driving behavior monitoring
Embedded machine learning-based road conditions and driving behavior monitoring
IJECEIAES
 
Manufacturing Process of molasses based distillery ppt.pptx
Manufacturing Process of molasses based distillery ppt.pptxManufacturing Process of molasses based distillery ppt.pptx
Manufacturing Process of molasses based distillery ppt.pptx
Madan Karki
 
ISPM 15 Heat Treated Wood Stamps and why your shipping must have one
ISPM 15 Heat Treated Wood Stamps and why your shipping must have oneISPM 15 Heat Treated Wood Stamps and why your shipping must have one
ISPM 15 Heat Treated Wood Stamps and why your shipping must have one
Las Vegas Warehouse
 
2008 BUILDING CONSTRUCTION Illustrated - Ching Chapter 02 The Building.pdf
2008 BUILDING CONSTRUCTION Illustrated - Ching Chapter 02 The Building.pdf2008 BUILDING CONSTRUCTION Illustrated - Ching Chapter 02 The Building.pdf
2008 BUILDING CONSTRUCTION Illustrated - Ching Chapter 02 The Building.pdf
Yasser Mahgoub
 
Understanding Inductive Bias in Machine Learning
Understanding Inductive Bias in Machine LearningUnderstanding Inductive Bias in Machine Learning
Understanding Inductive Bias in Machine Learning
SUTEJAS
 
BRAIN TUMOR DETECTION for seminar ppt.pdf
BRAIN TUMOR DETECTION for seminar ppt.pdfBRAIN TUMOR DETECTION for seminar ppt.pdf
BRAIN TUMOR DETECTION for seminar ppt.pdf
LAXMAREDDY22
 
IEEE Aerospace and Electronic Systems Society as a Graduate Student Member
IEEE Aerospace and Electronic Systems Society as a Graduate Student MemberIEEE Aerospace and Electronic Systems Society as a Graduate Student Member
IEEE Aerospace and Electronic Systems Society as a Graduate Student Member
VICTOR MAESTRE RAMIREZ
 
International Conference on NLP, Artificial Intelligence, Machine Learning an...
International Conference on NLP, Artificial Intelligence, Machine Learning an...International Conference on NLP, Artificial Intelligence, Machine Learning an...
International Conference on NLP, Artificial Intelligence, Machine Learning an...
gerogepatton
 
132/33KV substation case study Presentation
132/33KV substation case study Presentation132/33KV substation case study Presentation
132/33KV substation case study Presentation
kandramariana6
 
Optimizing Gradle Builds - Gradle DPE Tour Berlin 2024
Optimizing Gradle Builds - Gradle DPE Tour Berlin 2024Optimizing Gradle Builds - Gradle DPE Tour Berlin 2024
Optimizing Gradle Builds - Gradle DPE Tour Berlin 2024
Sinan KOZAK
 
Certificates - Mahmoud Mohamed Moursi Ahmed
Certificates - Mahmoud Mohamed Moursi AhmedCertificates - Mahmoud Mohamed Moursi Ahmed
Certificates - Mahmoud Mohamed Moursi Ahmed
Mahmoud Morsy
 

Kürzlich hochgeladen (20)

Casting-Defect-inSlab continuous casting.pdf
Casting-Defect-inSlab continuous casting.pdfCasting-Defect-inSlab continuous casting.pdf
Casting-Defect-inSlab continuous casting.pdf
 
22CYT12-Unit-V-E Waste and its Management.ppt
22CYT12-Unit-V-E Waste and its Management.ppt22CYT12-Unit-V-E Waste and its Management.ppt
22CYT12-Unit-V-E Waste and its Management.ppt
 
学校原版美国波士顿大学毕业证学历学位证书原版一模一样
学校原版美国波士顿大学毕业证学历学位证书原版一模一样学校原版美国波士顿大学毕业证学历学位证书原版一模一样
学校原版美国波士顿大学毕业证学历学位证书原版一模一样
 
spirit beverages ppt without graphics.pptx
spirit beverages ppt without graphics.pptxspirit beverages ppt without graphics.pptx
spirit beverages ppt without graphics.pptx
 
KuberTENes Birthday Bash Guadalajara - K8sGPT first impressions
KuberTENes Birthday Bash Guadalajara - K8sGPT first impressionsKuberTENes Birthday Bash Guadalajara - K8sGPT first impressions
KuberTENes Birthday Bash Guadalajara - K8sGPT first impressions
 
Transformers design and coooling methods
Transformers design and coooling methodsTransformers design and coooling methods
Transformers design and coooling methods
 
john krisinger-the science and history of the alcoholic beverage.pptx
john krisinger-the science and history of the alcoholic beverage.pptxjohn krisinger-the science and history of the alcoholic beverage.pptx
john krisinger-the science and history of the alcoholic beverage.pptx
 
Curve Fitting in Numerical Methods Regression
Curve Fitting in Numerical Methods RegressionCurve Fitting in Numerical Methods Regression
Curve Fitting in Numerical Methods Regression
 
Engineering Drawings Lecture Detail Drawings 2014.pdf
Engineering Drawings Lecture Detail Drawings 2014.pdfEngineering Drawings Lecture Detail Drawings 2014.pdf
Engineering Drawings Lecture Detail Drawings 2014.pdf
 
Embedded machine learning-based road conditions and driving behavior monitoring
Embedded machine learning-based road conditions and driving behavior monitoringEmbedded machine learning-based road conditions and driving behavior monitoring
Embedded machine learning-based road conditions and driving behavior monitoring
 
Manufacturing Process of molasses based distillery ppt.pptx
Manufacturing Process of molasses based distillery ppt.pptxManufacturing Process of molasses based distillery ppt.pptx
Manufacturing Process of molasses based distillery ppt.pptx
 
ISPM 15 Heat Treated Wood Stamps and why your shipping must have one
ISPM 15 Heat Treated Wood Stamps and why your shipping must have oneISPM 15 Heat Treated Wood Stamps and why your shipping must have one
ISPM 15 Heat Treated Wood Stamps and why your shipping must have one
 
2008 BUILDING CONSTRUCTION Illustrated - Ching Chapter 02 The Building.pdf
2008 BUILDING CONSTRUCTION Illustrated - Ching Chapter 02 The Building.pdf2008 BUILDING CONSTRUCTION Illustrated - Ching Chapter 02 The Building.pdf
2008 BUILDING CONSTRUCTION Illustrated - Ching Chapter 02 The Building.pdf
 
Understanding Inductive Bias in Machine Learning
Understanding Inductive Bias in Machine LearningUnderstanding Inductive Bias in Machine Learning
Understanding Inductive Bias in Machine Learning
 
BRAIN TUMOR DETECTION for seminar ppt.pdf
BRAIN TUMOR DETECTION for seminar ppt.pdfBRAIN TUMOR DETECTION for seminar ppt.pdf
BRAIN TUMOR DETECTION for seminar ppt.pdf
 
IEEE Aerospace and Electronic Systems Society as a Graduate Student Member
IEEE Aerospace and Electronic Systems Society as a Graduate Student MemberIEEE Aerospace and Electronic Systems Society as a Graduate Student Member
IEEE Aerospace and Electronic Systems Society as a Graduate Student Member
 
International Conference on NLP, Artificial Intelligence, Machine Learning an...
International Conference on NLP, Artificial Intelligence, Machine Learning an...International Conference on NLP, Artificial Intelligence, Machine Learning an...
International Conference on NLP, Artificial Intelligence, Machine Learning an...
 
132/33KV substation case study Presentation
132/33KV substation case study Presentation132/33KV substation case study Presentation
132/33KV substation case study Presentation
 
Optimizing Gradle Builds - Gradle DPE Tour Berlin 2024
Optimizing Gradle Builds - Gradle DPE Tour Berlin 2024Optimizing Gradle Builds - Gradle DPE Tour Berlin 2024
Optimizing Gradle Builds - Gradle DPE Tour Berlin 2024
 
Certificates - Mahmoud Mohamed Moursi Ahmed
Certificates - Mahmoud Mohamed Moursi AhmedCertificates - Mahmoud Mohamed Moursi Ahmed
Certificates - Mahmoud Mohamed Moursi Ahmed
 

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>