TUTORIAL HOME
AJAX Introduction
❮ Previous Next ❯
AJAX is a developer’s dream, because you can:
Update a web page without reloading the page
Request data from a server – after the page has loaded
Receive data from a server – after the page has loaded
Send data to a server – in the background
Examples in Every Chapter
In every chapter, you can edit the examples online, and click on a button to view the result.
AJAX Example
Let AJAX change this text
Change Content
»
AJAX Example Explained
HTML Page
Let AJAX change this text
Change Content
The HTML page contains a
The
The calls a function (if it is clicked).
The function requests data from a web server and displays it:
Function loadDoc()
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();
}
What is AJAX?
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.
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
❮ Previous Next ❯
AJAX – The XMLHttpRequest Object
TUTORIAL HOME
AJAX – The XMLHttpRequest Object
❮ Previous Next ❯
The keystone of AJAX is the XMLHttpRequest object.
The XMLHttpRequest Object
All modern browsers support the XMLHttpRequest object.
The XMLHttpRequest object is 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.
Create an XMLHttpRequest Object
All modern browsers (Chrome, IE7+, Firefox, Safari, and Opera) have a built-in XMLHttpRequest object.
Syntax for creating an XMLHttpRequest object:
variable = new XMLHttpRequest();
Old versions of Internet Explorer (IE5 and IE6) use an ActiveX Object:
variable = new ActiveXObject(“Microsoft.XMLHTTP”);
To handle all browsers, including IE5 and IE6, check if the browser supports the XMLHttpRequest object. If it does, create an XMLHttpRequest object, if not, create an ActiveXObject:
Example
var xhttp;
if (window.XMLHttpRequest) {
xhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xhttp = new ActiveXObject(“Microsoft.XMLHTTP”);
}
»
Access Across Domains
For security reasons, modern browsers do not allow access across domains.
This means that both the web page and the XML file it tries to load, must be located on the same server.
The examples on Omegas all open XML files located on the Omegas domain.
If you want to use the example above on one of your own web pages, the XML files you load must be located on your own server.
Old Versions of Internet Explorer (IE5 and IE6)
Old versions of Internet Explorer (IE5 and IE6) do not support the XMLHttpRequest object.
To handle IE5 and IE6, check if the browser supports the XMLHttpRequest object, or else create an ActiveXObject:
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
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”
For a complete list go to the Http Messages Reference
statusText Returns the status-text (e.g. “OK” or “Not Found”)
❮ Previous Next ❯
AJAX – Send a Request To a Server
TUTORIAL HOME
AJAX – Send a Request To a Server
❮ Previous Next ❯
The XMLHttpRequest object is used to exchange data with 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();
Method Description
open(method, url, async) Specifies the type of request
method: the type of request: GET or POST
url: the server (file) location
async: true (asynchronous) or false (synchronous)
send() Sends the request to the server (used for GET)
send(string) Sends the request to the server (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.html”, 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.html?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.html?fname=Henry&lname=Ford”, true);
xhttp.send();
»
POST Requests
A simple POST request:
Example
xhttp.open(“POST”, “demo_post.html”, 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”, “ajax_test.html”, true);
xhttp.setRequestHeader(“Content-type”, “application/x-www-form-urlencoded”);
xhttp.send(“fname=Henry&lname=Ford”);
»
Method Description
setRequestHeader(header, value) Adds HTTP headers to the request
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.html”, true);
The file can be any kind of file, like .txt and .xml, or server scripting files like .html and .php (which can perform actions on the server before sending the response back).
Asynchronous – True or False?
To send the request asynchronously, the async parameter of the open() method has to be set to true:
xhttp.open(“GET”, “ajax_test.html”, true);
Sending asynchronous requests is a huge improvement for web developers. Many of the tasks performed on the server are very time consuming. Before AJAX, this operation could cause the application to hang or stop.
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 when the response ready
Async = true
When using async = true, specify a function to execute when the response is ready in the onreadystatechange event:
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();
»
You will learn more about onreadystatechange in a later chapter.
Async = false
To use async=false, change the third parameter in the open() method to false:
xhttp.open(“GET”, “ajax_info.txt”, false);
Using async=false is not recommended, but for a few small requests this can be ok.
Remember that the JavaScript will NOT continue to execute, until the server response is ready. If the server is busy or slow, the application will hang or stop.
Note: When you use async=false, do NOT write an onreadystatechange function – just put the code after the send() statement:
Example
xhttp.open(“GET”, “ajax_info.txt”, false);
xhttp.send();
document.getElementById(“demo”).innerHTML = xhttp.responseText;
»
❮ Previous Next ❯
AJAX – Server Response
TUTORIAL HOME
AJAX – Server Response
❮ Previous Next ❯
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
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
status 200: “OK”
403: “Forbidden”
404: “Page not found”
For a complete list go to the Http Messages Reference
statusText Returns the status-text (e.g. “OK” or “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.onreadystatechange = function() {
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.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
}
»
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
getResponseHeader() Returns specific header information from the server resource
getAllResponseHeaders() Returns all the header 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;
»
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 + “
“;
}
document.getElementById(“demo”).innerHTML = txt;
xhttp.open(“GET”, “cd_catalog.xml”, true);
xhttp.send();
»
You will learn a lot more about XML DOM in the DOM chapters of this tutorial.
The getAllResponseHeaders() Method
The getAllResponseHeaders() method returns all header information from the server response.
Example
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
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.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById(“demo”).innerHTML =
this.getResponseHeader(“Last-Modified”);
}
};
xhttp.open(“GET”, “ajax_info.txt”, true);
xhttp.send();
»
❮ Previous Next ❯
AJAX XML Example
TUTORIAL HOME
AJAX XML Example
❮ Previous Next ❯
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
Get CD info
»
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.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=”
“;
var x = xmlDoc.getElementsByTagName(“CD”);
for (i = 0; i <x.length; i++) {
table += “
x[i].getElementsByTagName(“TITLE”)[0].childNodes[0].nodeValue +
“
x[i].getElementsByTagName(“ARTIST”)[0].childNodes[0].nodeValue +
“
“;
}
document.getElementById(“demo”).innerHTML = table;
}
The XML File
The XML file used in the example above looks like this: “cd_catalog.xml”.
❮ Previous Next ❯
AJAX PHP Example
TUTORIAL HOME
AJAX PHP Example
❮ Previous Next ❯
AJAX is used to create more interactive applications.
AJAX PHP Example
The following example demonstrates how a web page can communicate with a web server while a user types characters in an input field:
Example
Start typing a name in the input field below:
First name: 
Suggestions:
Example Explained
In the example above, when a user types a character in the input field, a function called “showHint()” is executed.
The function is triggered by the onkeyup event.
Here is the HTML code:
Example
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.responseText;
}
};
xmlhttp.open(“GET”, “gethint.php?q=” + str, true);
xmlhttp.send();
}
}
Start typing a name in the input field below:
First name: <input type="text" onkeyup="showHint(this.value)">
Suggestions:
»
Code explanation:
First, check if the input field is empty (str.length == 0). If it is, clear the content of the txtHint placeholder and exit the function.
However, if the input field is not empty, do the following:
Create an XMLHttpRequest object
Create the function to be executed when the server response is ready
Send the request off to a PHP file (gethint.php) on the server
Notice that q parameter is added gethint.php?q=”+str
The str variable holds the content of the input field
The PHP File – “gethint.php”
The PHP file checks an array of names, and returns the corresponding name(s) to the browser:
<?php
// Array with names
$a[] = “Anna”;
$a[] = “Brittany”;
$a[] = “Cinderella”;
$a[] = “Diana”;
$a[] = “Eva”;
$a[] = “Fiona”;
$a[] = “Gunda”;
$a[] = “Hege”;
$a[] = “Inga”;
$a[] = “Johanna”;
$a[] = “Kitty”;
$a[] = “Linda”;
$a[] = “Nina”;
$a[] = “Ophelia”;
$a[] = “Petunia”;
$a[] = “Amanda”;
$a[] = “Raquel”;
$a[] = “Cindy”;
$a[] = “Doris”;
$a[] = “Eve”;
$a[] = “Evita”;
$a[] = “Sunniva”;
$a[] = “Tove”;
$a[] = “Unni”;
$a[] = “Violet”;
$a[] = “Liza”;
$a[] = “Elizabeth”;
$a[] = “Ellen”;
$a[] = “Wenche”;
$a[] = “Vicky”;
// get the q parameter from URL
$q = $_REQUEST[“q”];
$hint = “”;
// lookup all hints from array if $q is different from “”
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”;
}
}
}
}
// Output “no suggestion” if no hint was found or output correct values
echo $hint === “” ? “no suggestion” : $hint;
?>
❮ Previous Next ❯
AJAX Examples
❮ Previous Next ❯
– Examples
Simple Examples
A simple AJAX example
Create a simple XMLHttpRequest, and retrieve data from a TXT file.
An AJAX example with a callback function
Create a XMLHttpRequest with a callback function, and retrieve data from a TXT file.
Examples explained
Request Header Information
Retrieve all header information of a resource (file)
Retrieve specific header information of a resource (file)
Examples explained
Request XML Files
Load an XML file with AJAX
Create an XMLHttpRequest to retrieve data from an XML file.
Retrieve the content of an XML file
Create an XMLHttpRequest to retrieve data from an XML file and display the data in an HTML table.
Examples explained
Retrieve Server Data with PHP and ASP
Retrieve the content of a PHP file
How a web page can communicate with a web server while a user type characters in an input field.
Retrieve the content of an ASP file
How a web page can communicate with a web server while a user type characters in an input field.
Examples explained
Retrieve Database Information
Retrieve content from a database
How a web page can fetch information from a database with AJAX.
Examples explained
AJAX Applications
View an XML CD catalog
Display XML data in an HTML table
Show XML data inside an HTML div element
Navigate through XML nodes
A simple CD catalog application
Examples explained
❮ Previous Next ❯
AJAX Database Example
TUTORIAL HOME
AJAX Database Example
❮ Previous Next ❯
AJAX can be used for interactive communication with a database.
AJAX Database Example
The following example will demonstrate how a web page can fetch information from a database with AJAX:
Example

Customer info will be listed here…
»
Example Explained – The showCustomer() Function
When a user selects a customer in the dropdown list above, a function called “showCustomer()” is executed. The function is triggered by the “onchange” event:
showCustomer
function showCustomer(str) {
var xhttp;
if (str == “”) {
document.getElementById(“txtHint”).innerHTML = “”;
return;
}
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById(“txtHint”).innerHTML = this.responseText;
}
};
xhttp.open(“GET”, “getcustomer.html?q=”+str, true);
xhttp.send();
}
The showCustomer() function does the following:
Check if a customer is selected
Create an XMLHttpRequest object
Create the function to be executed when the server response is ready
Send the request off to a file on the server
Notice that a parameter (q) is added to the URL (with the content of the dropdown list)
The AJAX Server Page
The page on the server called by the JavaScript above is an ASP file called “getcustomer.html”.
The server file could easily be rewritten in PHP, or some other server languages.
Look at a corresponding example in PHP.
The source code in “getcustomer.html” runs a query against a database, and returns the result in an HTML table:
<%
response.expires=-1
sql=”SELECT * FROM CUSTOMERS WHERE CUSTOMERID=”
sql=sql & “‘” & request.querystring(“q”) & “‘”
set conn=Server.CreateObject(“ADODB.Connection”)
conn.Provider=”Microsoft.Jet.OLEDB.4.0″
conn.Open(Server.Mappath(“/datafolder/northwind.mdb”))
set rs=Server.CreateObject(“ADODB.recordset”)
rs.Open sql,conn
response.write(“
| ” & x.name & “ | ” & x.value & “ |
“)
%>
❮ Previous Next ❯
AJAX ASP Example
❮ Previous Next ❯
AJAX is used to create more interactive applications.
AJAX ASP Example
The following example will demonstrate how a web page can communicate with a web server while a user type characters in an input field:
Example
Start typing a name in the input field below:
First name: 
Suggestions:
Example Explained
In the example above, when a user types a character in the input field, a function called “showHint()” is executed.
The function is triggered by the onkeyup event.
Here is the HTML code:
Example
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.responseText;
}
};
xmlhttp.open(“GET”, “gethint.html?q=” + str, true);
xmlhttp.send();
}
}
Start typing a name in the input field below:
First name: <input type="text" onkeyup="showHint(this.value)">
Suggestions:
»
Code explanation:
First, check if the input field is empty (str.length == 0). If it is, clear the content of the txtHint placeholder and exit the function.
However, if the input field is not empty, do the following:
Create an XMLHttpRequest object
Create the function to be executed when the server response is ready
Send the request off to an ASP file (gethint.html) on the server
Notice that q parameter is added gethint.html?q=”+str
The str variable holds the content of the input field
The ASP File – “gethint.html”
The ASP file checks an array of names, and returns the corresponding name(s) to the browser:
<%
response.expires=-1
dim a(30)
‘Fill up array with names
a(1)=”Anna”
a(2)=”Brittany”
a(3)=”Cinderella”
a(4)=”Diana”
a(5)=”Eva”
a(6)=”Fiona”
a(7)=”Gunda”
a(8)=”Hege”
a(9)=”Inga”
a(10)=”Johanna”
a(11)=”Kitty”
a(12)=”Linda”
a(13)=”Nina”
a(14)=”Ophelia”
a(15)=”Petunia”
a(16)=”Amanda”
a(17)=”Raquel”
a(18)=”Cindy”
a(19)=”Doris”
a(20)=”Eve”
a(21)=”Evita”
a(22)=”Sunniva”
a(23)=”Tove”
a(24)=”Unni”
a(25)=”Violet”
a(26)=”Liza”
a(27)=”Elizabeth”
a(28)=”Ellen”
a(29)=”Wenche”
a(30)=”Vicky”
‘get the q parameter from URL
q=ucase(request.querystring(“q”))
‘lookup all hints from array if length of q>0
if len(q)>0 then
hint=””
for i=1 to 30
if q=ucase(mid(a(i),1,len(q))) then
if hint=”” then
hint=a(i)
else
hint=hint & ” , ” & a(i)
end if
end if
next
end if
‘Output “no suggestion” if no hint were found
‘or output the correct values
if hint=”” then
response.write(“no suggestion”)
else
response.write(hint)
end if
%>
❮ Previous Next ❯



