Ajax Tutorial For Newbie

AJAX ( Asynchronous JavaScript and XML) is not a new programming language, but a technique for creating more interactive web applications. This tutorial will give you a very basic example about how to build a Ajax application. Most of Ajax applications consist of following fours basic steps:

  1. An HTML document
  2. JavaScript routines to create an instance of the XMLHTTPRequest object and construct and send asynchronous server calls
  3. A server-side routine(e.g. JSP,ASP,PHP etc) to configure and return the required information
  4. A callback function to deal with the returned data

First Step :Create an HTML document


<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<style>
.displaybox {
width:150px;
background-color:#ffffff;
border:3px solid #000000;
padding:10px;
font:22px normal verdana, helvetica, arial, sans-serif;
}
</style>
<title>Ajax Tutorial For Newbie</title>
<meta name="generator" content="Namo WebEditor">
</head>
<body bgcolor="white" text="black" link="blue" vlink="purple" alink="red">
<center>
<h6>Getting the server time without page refresh</h6>
<form>
<input type="button" value="Refresh" onClick="getServerTime()">
</form>
<div id="showtime" class="displaybox"></div>
</center>
</body>
</html>

Second Step: Adding JavaScript

At the heart of AJAX is the communication channel with your server. The best way to accomplish AJAX communication is by using XMLHttpRequest. XMLHttpRequest provides the ability to make synchronous and asynchronous requests while providing an easy-to-use programming model. Following code is to create an XMLHTTPRequest object:

function getXMLHTTPRequest() {
try {
req = new XMLHttpRequest();
} catch(error1) {
try {
req = new ActiveXObject("Msxml2.XMLHTTP");
} catch (error2) {
try {
req = new ActiveXObject("Microsoft.XMLHTTP");
} catch (error3) {
req = false;
}
}
}
return req;
}

Create a function to construct server request

var http = getXMLHTTPRequest();
function getServerTime() {
var phpurl = 'gettime.php';
randInt = parseInt(Math.random()*999999999999999);
var modurl = phpurl+"?rand="+randInt;
http.open("GET", modurl, true);
http.onreadystatechange = useHttpResponse;
http.send(null);
}

Third step:Create a Server-Side Script

<?php
header('Content-Type: text/xml');
echo "<?xml version="1.0" ?><clock1><timenow>" .date('H:i:s')."</timenow></clock1>";
?>

Last step:The Callback Function

function useHttpResponse() {
if (http.readyState == 4) {
if(http.status == 200) {
var timeValue = http.responseXML .getElementsByTagName("timenow")[0];
document.getElementById('showtime').innerHTML = timeValue.childNodes[0].nodeValue;
}
} else {
document.getElementById('showtime').innerHTML = 'Error!">';
}
}

Summary

From this tutorial you learned how create an instance of the XMLHTTPRequest object, parse XML received from the server using JavaScript DOM methods and update the displayed page with the received data

Ajax Online Demo

Leave a comment