Learn AJAX in 5 mins

First I want to give credits to the author of the tutorial Learn AJAX in 20 mins that I improved  to be less complicated and noob friendly 🙂

AJAX stands for (as if you would remember it) Asynchronous JavaScript and XML. and it is used to send and receive data from the server without having to refresh the entire page.

I assume you have a basic knowledge of HTML and PHP.

First create two empty php files, call the first test.php and the second ajax.php. test.php  is the file that will be displayed to the user, while ajax.php is the file that will be contacted by AJAX to send and receive data.

copy the following to test.php

<!DOCTYPE HTML PUBLIC “-//W3C//DTD HTML 4.01 Transitional//EN” “http://www.w3.org/TR/html4/loose.dtd”>

<meta http-equiv=”content-type” content=”text/html; charset=iso-8859-1″>
<meta name=”author” content=”PsMan”>



<script type=”text/javascript”>

var xmlhttp=false;

if (!xmlhttp && typeof XMLHttpRequest!=’undefined’) {
xmlhttp = new XMLHttpRequest();

function ajax_call() {

xmlhttp.open(“GET”, ‘ajax.php?num1=’ +
document.getElementById(‘t1’).value , true);

xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4) {
document.getElementById(‘t2’).value = xmlhttp.responseText;

return false;


<form action=”” onsubmit=”return ajax_call()”>
<input type=”text” name=”t1″ id=”t1″ “>
<input type=”text” name=”t2″ id=”t2″ >
<input type=”submit” value=”ok”>

I will not be explaining the HTML part. not in my 5 mins.
the Java script will be in charge of passing the data from and to the server. xmlhttp which is  XMLHttpRequest() is used to read whatever these is on the web-page supplied to it via xmlhttp.open.

the page we are opening with xmlhttp.open contains  some GET parameters that we want to pass to the server.

we will read and write the data on the page via document.getElementById which is obvious if you had any experience with java.

The contents of the second PHP file are

echo $a . $a ;

put both these files in the same folder of a php server and start test.php

  • this will simply get any data that is sent from the first field by the GET method and write it twice in the second field 😉
    • Don’t forget to add the “id” tag to all form fields you which to access by java
    • Remember to set action=”” in the form to be processed by AJAX, other wise the form will be traditionally submitted somewhere
    • you can activate ajax on each key press to generate instantaneous interaction (Google wave style 🙂 ) by adding onkeyup=”return ajax_call()” to the selected  form field
    • This have worked for me on Opera 10, IE8, and firefox

    Time is up!

    I hope this has been useful. You think you can top my 5mins ? bring it on !

    If there are anything you think  I should change or add, please comment. Or just say thanks if you feel like it!

    Leave a Reply