SlideShare une entreprise Scribd logo
1  sur  18
Unit-5
AJAX and Web Services
Contents
AJAX: Ajax Client Server Architecture-XML Http Request Object-
Call Back Methods; Web Services: Introduction- Java web services
Basics – Creating, Publishing, Testing and Describing a Web
services (WSDL)-Consuming a web service, Database Driven web
service from an application –SOAP.
What is AJAX?
• AJAX is an acronym for Asynchronous JavaScript and XML. It is a
group of inter-related technologies like JavaScript,
DOM, XML, HTML/XHTML, CSS, XMLHttpRequest etc.
• AJAX allows you to send and receive data asynchronously without
reloading the web page. So it is fast.
• AJAX allows you to send only important information to the server not the
entire page. So only valuable data from the client side is routed to the
server side. It makes your application interactive and faster.
Understanding Synchronous vs Asynchronous
Synchronous (Classic Web-Application Model)
A synchronous request blocks the client until operation completes i.e. browser is unresponsive. In such
case, javascript engine of the browser is blocked.
As you can see in the above image, full page is refreshed at request time and user is blocked until request
completes.
Asynchronous (AJAX Web-Application Model)
An asynchronous request doesn’t block the client i.e. browser is responsive. At that time, user can perform
another operations also. In such case, javascript engine of the browser is not blocked.
As you can see in the above image, full page is not refreshed at request time and user gets response from
the ajax engine.
How AJAX works? (AJAX Client-Server Achitecture)
AJAX communicates with the server using XMLHttpRequest object. Let's try to understand the flow of ajax or
how ajax works by the image displayed below.
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.
The XMLHttpRequest Object
An object of XMLHttpRequest is used for asynchronous communication between
client and server.
It performs following operations:
1.Sends data from the client in the background
2.Receives the data from the server
3.Updates the webpage without reloading it.
Properties of XMLHttpRequest object
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"
For a complete list go to the Http Messages Reference
statusText Returns the status-text (e.g. "OK" or "Not Found")
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 Methods
AJAX - Send a Request To a Server
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();
GET or POST?
GET is simpler and faster than POST, and can be used in most cases.
However, always use POST requests when:
•A cached file is not an option (update a file or database on the server).
•Sending a large amount of data to the server (POST has no size limitations).
•Sending user input (which can contain unknown characters), POST is more robust and secure than
GET.
A simple GET request:
xhttp.open("GET", "demo_get.php", true);
xhttp.send();
A simple POST request:
Example
xhttp.open("POST", "demo_post.php", true);
xhttp.send();
To POST data like an HTML form, add an HTTP header with setRequestHeader(). Specify
the data you want to send in the send() method:
Example
xhttp.open("POST", "demo_post2.asp", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send("fname=Henry&lname=Ford");
Asynchronous - True or False?
Server requests should be sent asynchronously.
The async parameter of the open() method should be set to true:
xhttp.open("GET", "ajax_test.asp", true);
By sending asynchronously, the JavaScript does not have to wait for the server response, but can
instead:
•execute other scripts while waiting for server response
•deal with the response after the response is ready
The onreadystatechange Property
With the XMLHttpRequest object you can define a function to be executed when the request
receives an answer.
The function is defined in the onreadystatechange property of the XMLHttpResponse object:
Example
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();
AJAX - Server Response
The onreadystatechange function is called every time the readyState changes.
When readyState is 4 and status is 200, the response is ready:
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();
}
ajax_info.txt
<h1>AJAX</h1>
<p>AJAX is not a programming language.</p>
<p>AJAX is a technique for accessing web servers from a web page.</p>
<p>AJAX stands for Asynchronous JavaScript And XML.</p>
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.
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
}
The responseText Property
The responseText property returns the server response as a JavaScript string, and you can use
it accordingly:
Example
document.getElementById("demo").innerHTML = xhttp.responseText;
The responseXML Property
The XML HttpRequest object has an in-built XML parser.
The responseXML property returns the server response as an XML DOM object.
Using this property you can parse the response as an XML DOM object:
Example
Request the file cd_catalog.xml and parse the response:
xmlDoc = xhttp.responseXML;
txt = "";
x = xmlDoc.getElementsByTagName("ARTIST");
for (i = 0; i < x.length; i++) {
txt += x[i].childNodes[0].nodeValue + "<br>";
}
document.getElementById("demo").innerHTML = txt;
xhttp.open("GET", "cd_catalog.xml", true);
xhttp.send();
AJAX XML Example
<!DOCTYPE html>
<html>
<style>
table,th,td {
border : 1px solid black;
border-collapse: collapse;
}
th,td {
padding: 5px;
}
</style>
<body>
<h1>The XMLHttpRequest Object</h1>
<button type="button" onclick="loadDoc()">Get my CD
collection</button>
<br><br>
<table id="demo"></table>
<script>
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();
}
function myFunction(xml) {
var i;
var xmlDoc = xml.responseXML;
var table="<tr><th>Artist</th><th>Title</th></tr>";
var x = xmlDoc.getElementsByTagName("CD");
for (i = 0; i <x.length; i++) {
table += "<tr><td>" +
x[i].getElementsByTagName("ARTIST")[0].childNodes[0].nodeV
alue +
"</td><td>" +
x[i].getElementsByTagName("TITLE")[0].childNodes[0].nodeVal
ue +
"</td></tr>";
}
document.getElementById("demo").innerHTML = table;
}
</script>
</body>
</html>
Unit-5.pptx

Contenu connexe

Similaire à Unit-5.pptx (20)

Introduction to ajax
Introduction to ajaxIntroduction to ajax
Introduction to ajax
 
Ajax
AjaxAjax
Ajax
 
Ajax
AjaxAjax
Ajax
 
Ajax
AjaxAjax
Ajax
 
Ajax presentation
Ajax presentationAjax presentation
Ajax presentation
 
PHP - Introduction to PHP AJAX
PHP -  Introduction to PHP AJAXPHP -  Introduction to PHP AJAX
PHP - Introduction to PHP AJAX
 
Ajax
AjaxAjax
Ajax
 
AJAX
AJAXAJAX
AJAX
 
AJAX
AJAXAJAX
AJAX
 
Ajax
AjaxAjax
Ajax
 
Ajax
AjaxAjax
Ajax
 
Ajax
AjaxAjax
Ajax
 
Ajax
AjaxAjax
Ajax
 
Ajax
AjaxAjax
Ajax
 
Ajax
AjaxAjax
Ajax
 
Ajax
AjaxAjax
Ajax
 
AJAX
AJAXAJAX
AJAX
 
AJAX
AJAXAJAX
AJAX
 
Ajax
AjaxAjax
Ajax
 
AJAX
AJAXAJAX
AJAX
 

Dernier

Brand Analysis for reggaeton artist Jahzel.
Brand Analysis for reggaeton artist Jahzel.Brand Analysis for reggaeton artist Jahzel.
Brand Analysis for reggaeton artist Jahzel.GabrielaMiletti
 
Booking open Available Pune Call Girls Ambegaon Khurd 6297143586 Call Hot In...
Booking open Available Pune Call Girls Ambegaon Khurd  6297143586 Call Hot In...Booking open Available Pune Call Girls Ambegaon Khurd  6297143586 Call Hot In...
Booking open Available Pune Call Girls Ambegaon Khurd 6297143586 Call Hot In...Call Girls in Nagpur High Profile
 
WhatsApp 📞 8448380779 ✅Call Girls In Salarpur Sector 81 ( Noida)
WhatsApp 📞 8448380779 ✅Call Girls In Salarpur Sector 81 ( Noida)WhatsApp 📞 8448380779 ✅Call Girls In Salarpur Sector 81 ( Noida)
WhatsApp 📞 8448380779 ✅Call Girls In Salarpur Sector 81 ( Noida)Delhi Call girls
 
Call Girls Hoodi Just Call 👗 7737669865 👗 Top Class Call Girl Service Bangalore
Call Girls Hoodi Just Call 👗 7737669865 👗 Top Class Call Girl Service BangaloreCall Girls Hoodi Just Call 👗 7737669865 👗 Top Class Call Girl Service Bangalore
Call Girls Hoodi Just Call 👗 7737669865 👗 Top Class Call Girl Service Bangaloreamitlee9823
 
TEST BANK For Evidence-Based Practice for Nurses Appraisal and Application of...
TEST BANK For Evidence-Based Practice for Nurses Appraisal and Application of...TEST BANK For Evidence-Based Practice for Nurses Appraisal and Application of...
TEST BANK For Evidence-Based Practice for Nurses Appraisal and Application of...robinsonayot
 
Top Rated Pune Call Girls Deccan ⟟ 6297143586 ⟟ Call Me For Genuine Sex Serv...
Top Rated  Pune Call Girls Deccan ⟟ 6297143586 ⟟ Call Me For Genuine Sex Serv...Top Rated  Pune Call Girls Deccan ⟟ 6297143586 ⟟ Call Me For Genuine Sex Serv...
Top Rated Pune Call Girls Deccan ⟟ 6297143586 ⟟ Call Me For Genuine Sex Serv...Call Girls in Nagpur High Profile
 
OSU毕业证留学文凭,制做办理
OSU毕业证留学文凭,制做办理OSU毕业证留学文凭,制做办理
OSU毕业证留学文凭,制做办理cowagem
 
Call Girls Hosur Just Call 👗 7737669865 👗 Top Class Call Girl Service Bangalore
Call Girls Hosur Just Call 👗 7737669865 👗 Top Class Call Girl Service BangaloreCall Girls Hosur Just Call 👗 7737669865 👗 Top Class Call Girl Service Bangalore
Call Girls Hosur Just Call 👗 7737669865 👗 Top Class Call Girl Service Bangaloreamitlee9823
 
Top Rated Pune Call Girls Warje ⟟ 6297143586 ⟟ Call Me For Genuine Sex Servi...
Top Rated  Pune Call Girls Warje ⟟ 6297143586 ⟟ Call Me For Genuine Sex Servi...Top Rated  Pune Call Girls Warje ⟟ 6297143586 ⟟ Call Me For Genuine Sex Servi...
Top Rated Pune Call Girls Warje ⟟ 6297143586 ⟟ Call Me For Genuine Sex Servi...Call Girls in Nagpur High Profile
 
0425-GDSC-TMU.pdf0425-GDSC-TMU.pdf0425-GDSC-TMU.pdf0425-GDSC-TMU.pdf
0425-GDSC-TMU.pdf0425-GDSC-TMU.pdf0425-GDSC-TMU.pdf0425-GDSC-TMU.pdf0425-GDSC-TMU.pdf0425-GDSC-TMU.pdf0425-GDSC-TMU.pdf0425-GDSC-TMU.pdf
0425-GDSC-TMU.pdf0425-GDSC-TMU.pdf0425-GDSC-TMU.pdf0425-GDSC-TMU.pdfssuserded2d4
 
Toxicokinetics studies.. (toxicokinetics evaluation in preclinical studies)
Toxicokinetics studies.. (toxicokinetics evaluation in preclinical studies)Toxicokinetics studies.. (toxicokinetics evaluation in preclinical studies)
Toxicokinetics studies.. (toxicokinetics evaluation in preclinical studies)sonalinghatmal
 
Résumé (2 pager - 12 ft standard syntax)
Résumé (2 pager -  12 ft standard syntax)Résumé (2 pager -  12 ft standard syntax)
Résumé (2 pager - 12 ft standard syntax)Soham Mondal
 
Get To Know About "Lauren Prophet-Bryant''
Get To Know About "Lauren Prophet-Bryant''Get To Know About "Lauren Prophet-Bryant''
Get To Know About "Lauren Prophet-Bryant''Lauren Prophet-Bryant
 
Nandini Layout Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangal...
Nandini Layout Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangal...Nandini Layout Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangal...
Nandini Layout Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangal...amitlee9823
 
Joshua Minker Brand Exploration Sports Broadcaster .pptx
Joshua Minker Brand Exploration Sports Broadcaster .pptxJoshua Minker Brand Exploration Sports Broadcaster .pptx
Joshua Minker Brand Exploration Sports Broadcaster .pptxsportsworldproductio
 
Delhi Call Girls South Delhi 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Call
Delhi Call Girls South Delhi 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip CallDelhi Call Girls South Delhi 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Call
Delhi Call Girls South Delhi 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Callshivangimorya083
 
CALL ON ➥8923113531 🔝Call Girls Nishatganj Lucknow best sexual service
CALL ON ➥8923113531 🔝Call Girls Nishatganj Lucknow best sexual serviceCALL ON ➥8923113531 🔝Call Girls Nishatganj Lucknow best sexual service
CALL ON ➥8923113531 🔝Call Girls Nishatganj Lucknow best sexual serviceanilsa9823
 
Production Day 1.pptxjvjbvbcbcb bj bvcbj
Production Day 1.pptxjvjbvbcbcb bj bvcbjProduction Day 1.pptxjvjbvbcbcb bj bvcbj
Production Day 1.pptxjvjbvbcbcb bj bvcbjLewisJB
 
Personal Brand Exploration - Fernando Negron
Personal Brand Exploration - Fernando NegronPersonal Brand Exploration - Fernando Negron
Personal Brand Exploration - Fernando Negronnegronf24
 
Call Girls Bidadi Just Call 👗 7737669865 👗 Top Class Call Girl Service Bangalore
Call Girls Bidadi Just Call 👗 7737669865 👗 Top Class Call Girl Service BangaloreCall Girls Bidadi Just Call 👗 7737669865 👗 Top Class Call Girl Service Bangalore
Call Girls Bidadi Just Call 👗 7737669865 👗 Top Class Call Girl Service Bangaloreamitlee9823
 

Dernier (20)

Brand Analysis for reggaeton artist Jahzel.
Brand Analysis for reggaeton artist Jahzel.Brand Analysis for reggaeton artist Jahzel.
Brand Analysis for reggaeton artist Jahzel.
 
Booking open Available Pune Call Girls Ambegaon Khurd 6297143586 Call Hot In...
Booking open Available Pune Call Girls Ambegaon Khurd  6297143586 Call Hot In...Booking open Available Pune Call Girls Ambegaon Khurd  6297143586 Call Hot In...
Booking open Available Pune Call Girls Ambegaon Khurd 6297143586 Call Hot In...
 
WhatsApp 📞 8448380779 ✅Call Girls In Salarpur Sector 81 ( Noida)
WhatsApp 📞 8448380779 ✅Call Girls In Salarpur Sector 81 ( Noida)WhatsApp 📞 8448380779 ✅Call Girls In Salarpur Sector 81 ( Noida)
WhatsApp 📞 8448380779 ✅Call Girls In Salarpur Sector 81 ( Noida)
 
Call Girls Hoodi Just Call 👗 7737669865 👗 Top Class Call Girl Service Bangalore
Call Girls Hoodi Just Call 👗 7737669865 👗 Top Class Call Girl Service BangaloreCall Girls Hoodi Just Call 👗 7737669865 👗 Top Class Call Girl Service Bangalore
Call Girls Hoodi Just Call 👗 7737669865 👗 Top Class Call Girl Service Bangalore
 
TEST BANK For Evidence-Based Practice for Nurses Appraisal and Application of...
TEST BANK For Evidence-Based Practice for Nurses Appraisal and Application of...TEST BANK For Evidence-Based Practice for Nurses Appraisal and Application of...
TEST BANK For Evidence-Based Practice for Nurses Appraisal and Application of...
 
Top Rated Pune Call Girls Deccan ⟟ 6297143586 ⟟ Call Me For Genuine Sex Serv...
Top Rated  Pune Call Girls Deccan ⟟ 6297143586 ⟟ Call Me For Genuine Sex Serv...Top Rated  Pune Call Girls Deccan ⟟ 6297143586 ⟟ Call Me For Genuine Sex Serv...
Top Rated Pune Call Girls Deccan ⟟ 6297143586 ⟟ Call Me For Genuine Sex Serv...
 
OSU毕业证留学文凭,制做办理
OSU毕业证留学文凭,制做办理OSU毕业证留学文凭,制做办理
OSU毕业证留学文凭,制做办理
 
Call Girls Hosur Just Call 👗 7737669865 👗 Top Class Call Girl Service Bangalore
Call Girls Hosur Just Call 👗 7737669865 👗 Top Class Call Girl Service BangaloreCall Girls Hosur Just Call 👗 7737669865 👗 Top Class Call Girl Service Bangalore
Call Girls Hosur Just Call 👗 7737669865 👗 Top Class Call Girl Service Bangalore
 
Top Rated Pune Call Girls Warje ⟟ 6297143586 ⟟ Call Me For Genuine Sex Servi...
Top Rated  Pune Call Girls Warje ⟟ 6297143586 ⟟ Call Me For Genuine Sex Servi...Top Rated  Pune Call Girls Warje ⟟ 6297143586 ⟟ Call Me For Genuine Sex Servi...
Top Rated Pune Call Girls Warje ⟟ 6297143586 ⟟ Call Me For Genuine Sex Servi...
 
0425-GDSC-TMU.pdf0425-GDSC-TMU.pdf0425-GDSC-TMU.pdf0425-GDSC-TMU.pdf
0425-GDSC-TMU.pdf0425-GDSC-TMU.pdf0425-GDSC-TMU.pdf0425-GDSC-TMU.pdf0425-GDSC-TMU.pdf0425-GDSC-TMU.pdf0425-GDSC-TMU.pdf0425-GDSC-TMU.pdf
0425-GDSC-TMU.pdf0425-GDSC-TMU.pdf0425-GDSC-TMU.pdf0425-GDSC-TMU.pdf
 
Toxicokinetics studies.. (toxicokinetics evaluation in preclinical studies)
Toxicokinetics studies.. (toxicokinetics evaluation in preclinical studies)Toxicokinetics studies.. (toxicokinetics evaluation in preclinical studies)
Toxicokinetics studies.. (toxicokinetics evaluation in preclinical studies)
 
Résumé (2 pager - 12 ft standard syntax)
Résumé (2 pager -  12 ft standard syntax)Résumé (2 pager -  12 ft standard syntax)
Résumé (2 pager - 12 ft standard syntax)
 
Get To Know About "Lauren Prophet-Bryant''
Get To Know About "Lauren Prophet-Bryant''Get To Know About "Lauren Prophet-Bryant''
Get To Know About "Lauren Prophet-Bryant''
 
Nandini Layout Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangal...
Nandini Layout Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangal...Nandini Layout Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangal...
Nandini Layout Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangal...
 
Joshua Minker Brand Exploration Sports Broadcaster .pptx
Joshua Minker Brand Exploration Sports Broadcaster .pptxJoshua Minker Brand Exploration Sports Broadcaster .pptx
Joshua Minker Brand Exploration Sports Broadcaster .pptx
 
Delhi Call Girls South Delhi 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Call
Delhi Call Girls South Delhi 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip CallDelhi Call Girls South Delhi 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Call
Delhi Call Girls South Delhi 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Call
 
CALL ON ➥8923113531 🔝Call Girls Nishatganj Lucknow best sexual service
CALL ON ➥8923113531 🔝Call Girls Nishatganj Lucknow best sexual serviceCALL ON ➥8923113531 🔝Call Girls Nishatganj Lucknow best sexual service
CALL ON ➥8923113531 🔝Call Girls Nishatganj Lucknow best sexual service
 
Production Day 1.pptxjvjbvbcbcb bj bvcbj
Production Day 1.pptxjvjbvbcbcb bj bvcbjProduction Day 1.pptxjvjbvbcbcb bj bvcbj
Production Day 1.pptxjvjbvbcbcb bj bvcbj
 
Personal Brand Exploration - Fernando Negron
Personal Brand Exploration - Fernando NegronPersonal Brand Exploration - Fernando Negron
Personal Brand Exploration - Fernando Negron
 
Call Girls Bidadi Just Call 👗 7737669865 👗 Top Class Call Girl Service Bangalore
Call Girls Bidadi Just Call 👗 7737669865 👗 Top Class Call Girl Service BangaloreCall Girls Bidadi Just Call 👗 7737669865 👗 Top Class Call Girl Service Bangalore
Call Girls Bidadi Just Call 👗 7737669865 👗 Top Class Call Girl Service Bangalore
 

Unit-5.pptx

  • 2. Contents AJAX: Ajax Client Server Architecture-XML Http Request Object- Call Back Methods; Web Services: Introduction- Java web services Basics – Creating, Publishing, Testing and Describing a Web services (WSDL)-Consuming a web service, Database Driven web service from an application –SOAP.
  • 3. What is AJAX? • AJAX is an acronym for Asynchronous JavaScript and XML. It is a group of inter-related technologies like JavaScript, DOM, XML, HTML/XHTML, CSS, XMLHttpRequest etc. • AJAX allows you to send and receive data asynchronously without reloading the web page. So it is fast. • AJAX allows you to send only important information to the server not the entire page. So only valuable data from the client side is routed to the server side. It makes your application interactive and faster.
  • 4. Understanding Synchronous vs Asynchronous Synchronous (Classic Web-Application Model) A synchronous request blocks the client until operation completes i.e. browser is unresponsive. In such case, javascript engine of the browser is blocked. As you can see in the above image, full page is refreshed at request time and user is blocked until request completes.
  • 5. Asynchronous (AJAX Web-Application Model) An asynchronous request doesn’t block the client i.e. browser is responsive. At that time, user can perform another operations also. In such case, javascript engine of the browser is not blocked. As you can see in the above image, full page is not refreshed at request time and user gets response from the ajax engine.
  • 6. How AJAX works? (AJAX Client-Server Achitecture) AJAX communicates with the server using XMLHttpRequest object. Let's try to understand the flow of ajax or how ajax works by the image displayed below. 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.
  • 7. The XMLHttpRequest Object An object of XMLHttpRequest is used for asynchronous communication between client and server. It performs following operations: 1.Sends data from the client in the background 2.Receives the data from the server 3.Updates the webpage without reloading it.
  • 8. Properties of XMLHttpRequest object 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" For a complete list go to the Http Messages Reference statusText Returns the status-text (e.g. "OK" or "Not Found")
  • 9. 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 Methods
  • 10. AJAX - Send a Request To a Server 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(); GET or POST? GET is simpler and faster than POST, and can be used in most cases. However, always use POST requests when: •A cached file is not an option (update a file or database on the server). •Sending a large amount of data to the server (POST has no size limitations). •Sending user input (which can contain unknown characters), POST is more robust and secure than GET. A simple GET request: xhttp.open("GET", "demo_get.php", true); xhttp.send();
  • 11. A simple POST request: Example xhttp.open("POST", "demo_post.php", true); xhttp.send(); To POST data like an HTML form, add an HTTP header with setRequestHeader(). Specify the data you want to send in the send() method: Example xhttp.open("POST", "demo_post2.asp", true); xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); xhttp.send("fname=Henry&lname=Ford");
  • 12. Asynchronous - True or False? Server requests should be sent asynchronously. The async parameter of the open() method should be set to true: xhttp.open("GET", "ajax_test.asp", true); By sending asynchronously, the JavaScript does not have to wait for the server response, but can instead: •execute other scripts while waiting for server response •deal with the response after the response is ready The onreadystatechange Property With the XMLHttpRequest object you can define a function to be executed when the request receives an answer. The function is defined in the onreadystatechange property of the XMLHttpResponse object: Example 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. AJAX - Server Response The onreadystatechange function is called every time the readyState changes. When readyState is 4 and status is 200, the response is ready: 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(); } ajax_info.txt <h1>AJAX</h1> <p>AJAX is not a programming language.</p> <p>AJAX is a technique for accessing web servers from a web page.</p> <p>AJAX stands for Asynchronous JavaScript And XML.</p>
  • 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. 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 }
  • 15. The responseText Property The responseText property returns the server response as a JavaScript string, and you can use it accordingly: Example document.getElementById("demo").innerHTML = xhttp.responseText; The responseXML Property The XML HttpRequest object has an in-built XML parser. The responseXML property returns the server response as an XML DOM object. Using this property you can parse the response as an XML DOM object: Example Request the file cd_catalog.xml and parse the response: xmlDoc = xhttp.responseXML; txt = ""; x = xmlDoc.getElementsByTagName("ARTIST"); for (i = 0; i < x.length; i++) { txt += x[i].childNodes[0].nodeValue + "<br>"; } document.getElementById("demo").innerHTML = txt; xhttp.open("GET", "cd_catalog.xml", true); xhttp.send();
  • 16. AJAX XML Example <!DOCTYPE html> <html> <style> table,th,td { border : 1px solid black; border-collapse: collapse; } th,td { padding: 5px; } </style> <body> <h1>The XMLHttpRequest Object</h1> <button type="button" onclick="loadDoc()">Get my CD collection</button> <br><br> <table id="demo"></table> <script> 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(); }
  • 17. function myFunction(xml) { var i; var xmlDoc = xml.responseXML; var table="<tr><th>Artist</th><th>Title</th></tr>"; var x = xmlDoc.getElementsByTagName("CD"); for (i = 0; i <x.length; i++) { table += "<tr><td>" + x[i].getElementsByTagName("ARTIST")[0].childNodes[0].nodeV alue + "</td><td>" + x[i].getElementsByTagName("TITLE")[0].childNodes[0].nodeVal ue + "</td></tr>"; } document.getElementById("demo").innerHTML = table; } </script> </body> </html>