Asynchronous Javascript and XML
Asynchronous Javascript and XML
Asynchronous Javascript and XML
• With AJAX you can create better, faster, and more user-friendly web
applications.
2
How does AJAX work?
• Pre-requisite:
– HTML/XHTML
– Javascript
3
First AJAX Application
testAjax.html
<html>
<body>
<form name="myForm">
Name: <input type="text" name="username" />
Time: <input type="text" name="time" />
</form>
</body>
</html>
4
First AJAX Application
<script type="text/javascript">
function ajaxFunction(){
var xmlHttp;
try {
// Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();
} catch (e) {
// Internet Explorer
try {
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
alert("Your browser does not support AJAX!");
return false;
}
}
}
}
</script>
5
More About the XMLHttpRequest Object
6
The onreadystatechange Property
• Method 1:
xmlHttp.onreadystatechange = function()
{
// We are going to write some code here
}
• Method 2:
xmlHttp.onreadystatechange = function
7
The readyState Property
State Description
xmlHttp.onreadystatechange = function()
{
if(xmlHttp.readyState==4)
{
// Get the data from the server's response
document.myForm.time.value=xmlHttp.responseText;
}
}
9
Sending Request to Server
• To send off a request to the server, we use the open()
method and the send() method.
<form name="myForm">
Name: <input type="text" onkeyup="ajaxFunction();" name="username" />
Time: <input type="text" name="time" />
</form>
10
First AJAX Application
<script type="text/javascript">
function ajaxFunction(){
var xmlHttp;
try {
// Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();
} catch (e) {
// Internet Explorer
try {
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
alert("Your browser does not support AJAX!");
return false;
}
}
}
xmlHttp.onreadystatechange=function()
{
if(xmlHttp.readyState==4)
{
document.myForm.time.value=xmlHttp.responseText;
}
}
xmlHttp.open("GET","time.asp",true);
xmlHttp.send(null);
}
</script>
11
Happy
AJAX
Programming!
Reference: http://www.w3schools.com/ajax/default.asp