AJAX Basic Tutorial

Introduction

AJAX, or Asynchronous JavaScript and XML, is a web technology that is based on JavaScript and HTTP requests. By using AJAX we can use JavaScript to get/send data from/to a server without reloading the whole webpage with the help of XMLHttpRequest object. AJAX uses asynchronous data transfer (HTTP requests) between the browser and the web server, allowing web pages to request small bits of information from the server instead of whole pages. The data received from web server is in XML format, and then we use JavaScript to parse that XML and do something useful with it.
 

AJAX works with any server-side technology, including PHP, Perl, ASP (.NET), Python, Ruby, ColdFusion, SSI, JSP, etc. So by using AJAX you can make your webpage dynamic, smaller and user-friendly. Also you can place ‘rich media contents’ on your webpage.

 

XMLHttpRequest object

Suppose if we have to develop a user registration page. If we use traditional JavaScript method after the user fills the form he or she will have to click the submit button and after that request will be processed and a new page will be loaded accordingly. But if we use AJAX upon submission the user stays on the same page and transfer of data takes place in the background. It’s much more user-friendly and also you can provide some additional features such as username suggestions, checking username availability and all this can be done automatically when user enters data without reloading the page.
When using AJAX, XMLHttpRequest is used by JavaScript for communicating directly with the web server.

 

My First AJAX Application

So let’s begin by taking up an example. Create a simple HTML page myAJAX.html as shown below

<html>
<body>

<form name="myAJAXForm">
Name: <input type="text" name="name" />
Current Date: <input type="text" name="time" />
</form>

</body>
</html>

This HTML page has a two textboxes – one where user will enter his name and the other one displays current date. We will request date data directly from the web server.

Now create a php page date.php which prints out the current date

<?php
$t=time();
echo(date("D F d Y",$t));
?>

Once you have done this now we need to add additional code to our HTML page to be able to use AJAX.

<script type="text/javascript">
function setupAJAX()
{
var xmlhttp;
if (window.XMLHttpRequest)
  {
  // code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else if (window.ActiveXObject)
  {
  // code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
else
  {
  alert("Sorry, your browser seems to not support XMLHTTP functionality.");
  }
}
</script>

The above code checks to whether the user’s browser supports XMLHTTP or not.

 

Sending a request to a server

xmlhttp.open("GET","date.php",true);
/*It has been assumed here that date.php is in the same directory.*/
xmlhttp.send(null);

The open() method takes three arguments as described below -

  • First argument – The method to use while sending request to the web server i.e. GET or POST.
  • Second argument – URL of the server side script
  • Third argument – Boolean to specify whether the request should be handled asynchronously or not.

 
The send() method is used to the request to the server.

 

The onreadystatechange Property

After sending a request to the web server, we need a function to receive the data returned from the server.

The onreadystatechange property stores the function that will process the response from a server. This function is stored in the property and is called automatically.

Syntax:-
xmlhttp.onreadystatechange=function()
{
// code here
}

 

The readyState property

The readyState property stores the current status of the server's response. Whenever readyState property changes, the onreadystatechange function is executed.

Possible values for the readyState property:

State Description
0 The request is not initialized
1 The request has been set up
2 The request has been sent
3 The request is in process
4 The request is complete

 

To get data from the web server we should first of all check the status of readyState property i.e. whether the request we made has been completed or not. So we add an If statement condition to the onreadystatechange function to test if the request we made is complete:

xmlhttp.onreadystatechange=function()
{
if(xmlhttp.readyState==4)
  {
  // Now we can get data from the server's response
  }
}

 

The responseText property

The responseText property is used to retrieve the data sent from the server.

In our case we want the place the data received from the server into the time textbox.

xmlhttp.onreadystatechange=function()
{
if(xmlhttp.readyState==4)
  {
  document.myAJAXForm.time.value=xmlhttp.responseText;
  }
}

Also we need to change our HTML page code so that whenever there is any change in ‘name’ textbox setupAJAX() function is executed as shown below.

<form name="myAJAXForm">
Name: <input type="text" name="name" onkeyup="setupAJAX();" />
Current Date: <input type="text" name="time" />
</form>

So now the complete code of HTML page myAJAX.html will be –

<html>
<body>

<script type="text/javascript">
function setupAJAX()
{
var xmlhttp;
if (window.XMLHttpRequest)
  {
  // code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else if (window.ActiveXObject)
  {
  // code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
else
  {
  alert("Sorry, your browser seems to not support XMLHTTP functionality!");
  }
xmlhttp.onreadystatechange=function()
{
if(xmlhttp.readyState==4)
  {
  document.myAJAXForm.time.value=xmlhttp.responseText;
  }
}
xmlhttp.open("GET","date.php",true);
xmlhttp.send(null);
}
</script>

<form name="myAJAXForm">
Name: <input type="text" name="name" onkeyup="setupAJAX();" />
Current Date: <input type="text" name="time" />
</form>

</body>
</html>
 

Output of My First AJAX Application


The output of the above code is shown below. Try it out now!

Name: Current Date:

 


Now you can create your own web-pages with AJAX. Goto next AJAX Search tutorial where some more advanced features are covered. If you have any question or query post it here!