Nothing Special   »   [go: up one dir, main page]

Unit II Ajax

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 46

Ajax

Unit-II (Part-II)
Unit II: Ajax(Part-II)
 Introduction to AJAX
 XMLHTTP
 Ajax Request
 Ajax Response
 Ajax Events
 Ajax XML file
Introduction to Ajax
 AJAX stands for Asynchronous JavaScript and XML. AJAX
is a new technique for creating better, faster, and more
interactive web applications with the help of XML, HTML,
CSS, and Java Script.
 Ajax uses XHTML for content, CSS for presentation, along
with Document Object Model and JavaScript for dynamic
content display.
 Conventional web applications transmit information to and
from the sever using synchronous requests. It means you fill
out a form, hit submit, and get directed to a new page with
new information from the server.
 With AJAX, when you hit submit, JavaScript will make a
request to the server, interpret the results, and update the
current screen. In the purest sense, the user would never
know that anything was even transmitted to the server.
 XML is commonly used as the format for receiving server
data, although any format, including plain text, can be used.
 AJAX is a web browser technology independent of web
server software.
 A user can continue to use the application while the client
program requests information from the server in the
background.
 Intuitive and natural user interaction. Clicking is not
required, mouse movement is a sufficient event trigger.
 Data-driven as opposed to page-driven.
Rich Internet Application Technology
 AJAX is the most viable Rich Internet Application
(RIA) technology so far. It is getting tremendous
industry momentum and several tool kit and
frameworks are emerging. But at the same time,
AJAX has browser incompatibility and it is
supported by JavaScript, which is hard to maintain
and debug.
AJAX is Based on Open Standards
 AJAX is based on the following open standards −
 Browser-based presentation using HTML and
Cascading Style Sheets (CSS).
 Data is stored in XML format and fetched from the
server.
 Behind-the-scenes data fetches using
XMLHttpRequest objects in the browser.
 JavaScript to make everything happen.
AJAX cannot work independently. It is used in combination with
other technologies to create interactive webpages.
JavaScript
 Loosely typed scripting language.
 JavaScript function is called when an event occurs in a page.
 Glue for the whole AJAX operation.

DOM
 API for accessing and manipulating structured documents.
 Represents the structure of XML and HTML documents.

CSS
 Allows for a clear separation of the presentation style from the
content and may be changed programmatically by JavaScript
XMLHttpRequest
 JavaScript object that performs asynchronous interaction with the
server.
 AJAX = Asynchronous JavaScript And XML.
 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)
 AJAX is a misleading name. 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.
Ajax working Model diagram
 An event occurs in a web page (the page is loaded,
a button is clicked)
 An XMLHttpRequest object is created by
JavaScript
 The XMLHttpRequest object sends a request to a
web server
 The server processes the request
 The server sends a response back to the web page
 The response is read by JavaScript
 Proper action (like page update) is performed by
JavaScript
Sample Example of Ajax
<!DOCTYPE html>
<html>
<body>
<div id="demo">
<h1>The XMLHttpRequest Object</h1>
<button type="button"
Content</button>
</div>
<script>
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp. {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML =
this.responseText;
}
};
xhttp.open("GET", "ajax_info.txt", true);
xhttp.send();
}
</script>
</body>
</html>
Ajax -XMLHTTP
 The XMLHttpRequest object is the key to AJAX. It has been
available ever since Internet Explorer 5.5 was released in July
2000, but was not fully discovered until AJAX and Web 2.0 in
2005 became popular.
 XMLHttpRequest (XHR) is an API that can be used by
JavaScript, JScript, VBScript, and other web browser scripting
languages to transfer and manipulate XML data to and from a
webserver using HTTP, establishing an independent connection
channel between a webpage's Client-Side and Server-Side.
 The data returned from XMLHttpRequest calls will often be
provided by back-end databases. Besides XML,
XMLHttpRequest can be used to fetch data in other formats,
e.g. JSON or even plain text.
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.
 The XMLHttpRequest object is used to exchange
data with a server.
Create an XMLHttpRequest Object
 All modern browsers (Chrome, Firefox, IE7+,
Edge, Safari Opera) have a built-in
XMLHttpRequest object.
 Syntax for creating an XMLHttpRequest object:

variable = new XMLHttpRequest();


 Example

var xhttp = new XMLHttpRequest();


Old Versions of Internet Explorer (IE5 and IE6)
 Old versions of Internet Explorer (IE5 and IE6) use an
ActiveX object instead of the XMLHttpRequest object:
variable = new ActiveXObject("Microsoft.XMLHTTP");
 To handle IE5 and IE6, check if the browser supports the
XMLHttpRequest object, or else create an ActiveX object:
Example
if (window.XMLHttpRequest) {
// code for modern browsers
xmlhttp = new XMLHttpRequest();
} else {
// code for old IE browsers
xmlhttp = new
ActiveXObject("Microsoft.XMLHTTP");
}
XMLHttpRequest Object Methods
Method Description
Creates a new XMLHttpRequest
new XMLHttpRequest()
object
abort() Cancels the current request
getAllResponseHeaders() Returns header information
getResponseHeader() Returns specific header information
Specifies the request

method: the request type GET or


POST
open(method,url,async,user,psw) url: the file location
async: true (asynchronous) or false
(synchronous)
user: optional user name
psw: optional password
Method Description

Sends the request to the server


send()
Used for GET requests

Sends the request to the server.


send(string)
Used for POST requests

Adds a label/value pair to the header


setRequestHeader()
to be sent
XMLHttpRequest Object Properties

Property Description

Defines a function to be called when the


onreadystatechange
readyState property changes

Holds the status of the XMLHttpRequest.


0: request not initialized
1: server connection established
readyState
2: request received
3: processing request
4: request finished and response is ready
Property Description
responseText Returns the response data as a string
responseXML Returns the response data as XML data
Returns the status-number of a request
200: "OK"
403: "Forbidden"
status
404: "Not Found"
For a complete list go to the
Http Messages Reference
Returns the status-text (e.g. "OK" or "Not
statusText
Found")
Ajax Request
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();
Method Description
Specifies the type of request

method: the type of request:


open(method, url, async) GET or POST
url: the server (file) location
async: true (asynchronous) or
false (synchronous)
Sends the request to the server
send()
(used for GET)
Sends the request to the server
send(string)
(used for POST)
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.
GET Requests
A simple GET request:
Example
xhttp.open("GET", "demo_get.asp", true);
xhttp.send();
In the example above, you may get a cached result. To avoid this, add
a unique ID to the URL:
Example
xhttp.open("GET", "demo_get.asp?t=" + Math.random(), true);
xhttp.send();
If you want to send information with the GET method, add the
information to the URL:
Example
xhttp.open("GET", "demo_get2.asp?
fname=Henry&lname=Ford", true);
xhttp.send();
POST Requests
A simple POST request:
Example
xhttp.open("POST", "demo_post.asp", 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");
Method Description
Adds HTTP headers to the
request
setRequestHeader(header,
value) header: specifies the header
name
value: specifies the header value
The url - A File On a Server
 The url parameter of the open() method, is an
address to a file on a server:
xhttp.open("GET", "ajax_test.asp", true);
 The file can be any kind of file, like .txt and .xml,
or server scripting files like .asp and .php (which
can perform actions on the server before sending
the response back).
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. {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML =
this.responseText;
}
};
xhttp.open("GET", "ajax_info.txt", true);
xhttp.send();
Synchronous Request
 To execute a synchronous request, change the third
parameter in the open() method to false:
xhttp.open("GET", "ajax_info.txt", false);
 Sometimes async = false are used for quick testing. You
will also find synchronous requests in older JavaScript
code.
 Since the code will wait for server completion, there is
no need for an onreadystatechange function:
Example
xhttp.open("GET", "ajax_info.txt", false);
xhttp.send();
document.getElementById("demo").innerHTML =
xhttp.responseText;
 Synchronous XMLHttpRequest (async = false) is
not recommended because the JavaScript will stop
executing until the server response is ready. If the
server is busy or slow, the application will hang or
stop.
 Synchronous XMLHttpRequest is in the process of
being removed from the web standard, but this
process can take many years.
 Modern developer tools are encouraged to warn
about using synchronous requests and may throw
an InvalidAccessError exception when it occurs.
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.
Property Description
Defines a function to be called when
onreadystatechange
the readyState property changes
Holds the status of the
XMLHttpRequest.
0: request not initialized
1: server connection established
readyState
2: request received
3: processing request
4: request finished and response is
ready
200: "OK"
403: "Forbidden"
status 404: "Page not found"
For a complete list go to the
Http Messages Reference
Returns the status-text (e.g. "OK" or
statusText
"Not Found")
 The onreadystatechange function is called every time the
readyState changes.
 When readyState is 4 and status is 200, the response is ready:

Example
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp. {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML =
this.responseText;
}
};
xhttp.open("GET", "ajax_info.txt", true);
xhttp.send();
}
 The onreadystatechange event is triggered four times (1-4), one
time for each change in the readyState.
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.
Example
loadDoc("url-1", myFunction1);

loadDoc("url-2", myFunction2);
function loadDoc(url, cFunction) {
var xhttp;
xhttp=new XMLHttpRequest();
xhttp. {
if (this.readyState == 4 && this.status == 200) {
myFunction1(this);
}
};
xhttp.open("GET", url, true);
xhttp.send();
}

function myFunction1(xhttp) {
// action goes here
}
function myFunction2(xhttp) {
// action goes here
}
Ajax Response
 Server Response Properties

Property Description

responseText get the response data as a string

responseXML get the response data as XML data


 Server Response Methods

Method Description

Returns specific header


getResponseHeader() information from the server
resource

Returns all the header


getAllResponseHeaders() information from the server
resource
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;
Ajax XML
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();
The getAllResponseHeaders() Method
 The getAllResponseHeaders() method returns all
header information from the server response.
Example
var xhttp = new XMLHttpRequest();
xhttp. {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML =
this.getAllResponseHeaders();
}
};
The getResponseHeader() Method
 The getResponseHeader() method returns specific header
information from the server response.
Example
var xhttp = new XMLHttpRequest();
xhttp. {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML =
this.getResponseHeader("Last-Modified");
}
};
xhttp.open("GET", "ajax_info.txt", true);
xhttp.send();
 AJAX can be used for interactive communication with an
XML file
AJAX XML Example
 The following example will demonstrate how a web
page can fetch information from an XML file with
AJAX:
Example Explained
 When a user clicks on the "Get CD info" button above,
the loadDoc() function is executed.
 The loadDoc() function creates an XMLHttpRequest
object, adds the function to be executed when the server
response is ready, and sends the request off to the server.
 When the server response is ready, an HTML table is
built, nodes (elements) are extracted from the XML file,
and it finally updates the element "demo" with the
HTML table filled with XML data:
LoadXMLDoc()
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp. {
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>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].nodeValue +
"</td><td>" +
x[i].getElementsByTagName("ARTIST")
[0].childNodes[0].nodeValue +
"</td></tr>";
}
document.getElementById("demo").innerHTML = table;
}

You might also like