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

Ajax

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 17

AJAX

What is AJAX?
AJAX = Asynchronous JavaScript And XML.

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 allows web pages to be updated asynchronously by


exchanging data with a web server. This means that it is
possible to update parts of a web page, without reloading
the whole page.

How AJAX Works:


 1. An event occurs in a web page (the page is loaded, a
button is clicked)
 2. An XMLHttpRequest object is created by JavaScript
 3. The XMLHttpRequest object sends a request to a web
server
 4. The server processes the request
 5. The server sends a response back to the web page
 6. The response is read by JavaScript
 7. Proper action (like page update) is performed by
JavaScript

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.

Creating an XMLHttpRequest Object:


Syntax for creating an XMLHttpRequest object:

var varname = new XMLHttpRequest();


Example:
var xhttp = new XMLHttpRequest();
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(header,value) Adds HTTP headers to the
request
header: specifies the header
name
value: specifies the header
value

XMLHttpRequest Object Properties:

Property Description

onreadystatechange Defines a function to be


called/executed 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")

Send a Request To a Server:


To send a request to a server, open() and send()
methods of the XMLHttpRequest object are used:

Example:
xhttp.open("GET", "demo_get.asp", true);
xhttp.send();
xhttp.open("GET", "ajax_info.txt", true);
xhttp.send();

If you want to send information with the GET method,


add the information to the URL:

xhttp.open("GET", "demo_get2.asp?
fname=Henry&lname=Ford", true);
xhttp.send();
To add an HTTP header with setRequestHeader(). Specify
the data you want to send in the send() method:

xhttp.open("POST", "demo_post2.asp", true);


xhttp.setRequestHeader("Content-type", "application/x-
www-form-urlencoded");
xhttp.send("fname=Henry&lname=Ford");

Asynchronous:
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 onreadystatechange function is called every time the


readyState changes.

When readyState is 4 and status is 200, the response is


ready.

The responseText property returns the server response


as a JavaScript string.

<!DOCTYPE html>
<html>
<body>
<div id="demo">
<h1>The XMLHttpRequest Object</h1>
<button type="button" >Content</button>
</div>
<script>
function loadDoc() {
var xhttp = new XMLHttpRexquest();
http. {
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_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>

The responseXML Property:


The responseXML property returns the server response
as an XML DOM object.

cd_catalog.xml
<CATALOG>
<CD>
<TITLE>Empire Burlesque</TITLE>
<ARTIST>Bob Dylan</ARTIST>
<COUNTRY>USA</COUNTRY>
<COMPANY>Columbia</COMPANY>
<PRICE>10.90</PRICE>
<YEAR>1985</YEAR>
</CD>
<CD>
<TITLE>Hide your heart</TITLE>
<ARTIST>Bonnie Tyler</ARTIST>
<COUNTRY>UK</COUNTRY>
<COMPANY>CBS Records</COMPANY>
<PRICE>9.90</PRICE>
<YEAR>1988</YEAR>
</CD>
<CD>
<TITLE>Greatest Hits</TITLE>
<ARTIST>Dolly Parton</ARTIST>
<COUNTRY>USA</COUNTRY>
<COMPANY>RCA</COMPANY>
<PRICE>9.90</PRICE>
<YEAR>1982</YEAR>
</CD>
<CD>
<TITLE>Still got the blues</TITLE>
<ARTIST>Gary Moore</ARTIST>
<COUNTRY>UK</COUNTRY>
<COMPANY>Virgin records</COMPANY>
<PRICE>10.20</PRICE>
<YEAR>1990</YEAR>
</CD>
</CATALOG>
ajaxdemo.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" my CD


collection</button>
<br><br>
<table id="demo"></table>

<script>
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>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].nodeValue +
"</td><td>" +
x[i].getElementsByTagName("TITLE")
[0].childNodes[0].nodeValue +
"</td></tr>";
}
document.getElementById("demo").innerHTML = table;
}
</script>
</body>
</html>

XML DOM Change Node Values:


The nodeValue property is used to change a node value.
The below code changes the text node value of the first
<title> element.
<html>
<body>
<p id="demo"></p>

<script>
var xhttp = new XMLHttpRequest();
xhttp. {
if (this.readyState == 4 && this.status == 200) {
myFunction(this);
}
};
xhttp.open("GET", "books.xml", true);
xhttp.send();

function myFunction(xml) {
var xmlDoc = xml.responseXML;
var x;
var txt = "";
x = xmlDoc.getElementsByTagName("title")[0].childNodes[0];
txt += x.nodeValue + "<br>";
x.nodeValue = "Easy Cooking";
x = xmlDoc.getElementsByTagName("title")[0].childNodes[0];
txt += x.nodeValue + "<br>";
document.getElementById("demo").innerHTML = txt;
}
</script>
</body>
</html>

Changing the Value of an Attribute


The setAttribute() method changes the value of an attribute.
The below code changes the category attribute of the <book> element.
<html>
<body>
<p id="demo"></p>
<script>
var xhttp = new XMLHttpRequest();
xhttp. {
if (this.readyState == 4 && this.status == 200) {
myFunction(this);
}
};
xhttp.open("GET", "books.xml", true);
xhttp.send();
function myFunction(xml) {
var xmlDoc = xml.responseXML;
var x = xmlDoc.getElementsByTagName('book');
x[0].setAttribute("category","food");
document.getElementById("demo").innerHTML =
x[0].getAttribute("category");
}
</script>
</body>
</html>
Changing the value of an Attribute Using nodeValue
The below code changes the category attribute of the
<book> element Using nodeValue.

<html>
<body>
<p id="demo"></p>
<script>
var xhttp = new XMLHttpRequest();
xhttp. {
if (this.readyState == 4 && this.status == 200) {
myFunction(this);
}
};
xhttp.open("GET", "books.xml", true);
xhttp.send();

function myFunction(xml) {
var xmlDoc = xml.responseXML;
var x = xmlDoc.getElementsByTagName("book")[0]
var y = x.getAttributeNode("category");
var txt = y.nodeValue + "<br>";
y.nodeValue ="food";
txt += y.nodeValue;
document.getElementById("demo").innerHTML = txt;
}
</script>
</body>
</html>
XML DOM Removing Nodes
The removeChild() method removes a specified node.

When a node is removed, all its child nodes are also removed.

The removeAttribute() method removes a specified attribute.

The below code will remove the first <book> element from the loaded
books.xml:

<html>
<body>
<p id="demo"></p>
<script>
var xhttp = new XMLHttpRequest();
xhttp. {
if (this.readyState == 4 && this.status == 200) {
myFunction(this);
}
};
xhttp.open("GET", "books.xml", true);
xhttp.send();

function myFunction(xml) {
var xmlDoc = xml.responseXML;
var root = xmlDoc.documentElement;
var currNode = root.childNodes[1];
removedNode =
currNode.removeChild(currNode.childNodes[1]);
document.getElementById("demo").innerHTML =
"Removed node: " + removedNode.nodeName;
}
</script>
</body>
</html>

The below code removes the "category" attribute in the


first <book> element:
<html>
<body>
<p id="demo"></p>
<script>
var xhttp = new XMLHttpRequest();
xhttp. {
if (this.readyState == 4 && this.status == 200) {
myFunction(this);
}
};
xhttp.open("GET", "books.xml", true);
xhttp.send();

function myFunction(xml) {
var xmlDoc = xml.responseXML;
var x = xmlDoc.getElementsByTagName("book");
document.getElementById("demo").innerHTML =
x[0].getAttribute('category') + "<br>";

x[0].removeAttribute('category');
document.getElementById("demo").innerHTML +=
x[0].getAttribute('category');
}
</script>
</body>
</html>
XML DOM Creating Nodes
The createElement() method creates a new element
node.

The below code Create a new element node <edition>


and append it node to the first <book> element.

<html>
<body>
<p id="demo"></p>
<script>
var xhttp = new XMLHttpRequest();
xhttp. {
if (this.readyState == 4 && this.status == 200) {
myFunction(this);
}
};
xhttp.open("GET", "books.xml", true);
xhttp.send();

function myFunction(xml) {
var x, y, i, newElement, txt, xmlDoc;
xmlDoc = xml.responseXML;
newElement = xmlDoc.createElement("edition");
x = xmlDoc.getElementsByTagName("book")[0]
x.appendChild(newElement);

// Display all elements


xlen = x.childNodes.length;
y = x.firstChild;
txt = "";
for (i = 0; i < xlen; i++) {
if (y.nodeType == 1) {
txt += y.nodeName + "<br>";
}
y = y.nextSibling;
}
document.getElementById("demo").innerHTML = txt;
}
</script>
</body>
</html>

You might also like