How To: Learn AJAX in 20 minutes

Here is a quick overview and example of AJAX in action. Before you begin, this example will only work in FireFox work in FireFox and IE7. You’ll have to change few things in the JavaScript for it to work in IE6. To download the files used below click here. If you don’t have PHP/Apache installed, follow the tutorial I made to install it. The example below assumes you know the basics of PHP, you can learn as you go along if you don’t. A good reference is the base PHP website.

AJAX stands for Asynchronous JavaScript and XML. Conventional web application trasmit information to and from the sever using synchronous requests. This means you fill out a form, hit submit, and get directed to a new page with new information from the server. With AJAX when submit is pressed, JavaScript will make a request to the server, interpret the results and update the current screen. In the purest sense, the user would never know that anything was even transmitted to the server.

A classic example of AJAX is Google Maps. If you havent noticed, with Google Maps you have the ability to click and drag the map. If you drag the map fast enough, you would see the new regions of the map loading in real-time. This is accomplished using AJAX.

If you click here, you’ll see a simple example of AJAX. The example performs the multiplication of two numbers. The top form performs the calculation using AJAX, while the bottom form uses standard techniques.

The Javascript that makes the example work is below. Basically an XMLHttpRequest is used to communicate with the server. Though the name may make you think you need to trasmit XML, it is not necessary (my example doesn’t). So when the function ajax_call() is executed, the already instantiated XMLHttpRequest attemps to open ajaxWork.php (with some parameters). Upon returning from the request (and assuming it was successful) the results are populated into the results input box.

Code:
var xmlhttp=false;

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

function ajax_call() {
     xmlhttp.open("GET", 'ajaxWork.php?num1=' +
           document.getElementById('num1').value +
                '&num2=' + document.getElementById('num2').value , true);

     xmlhttp.onreadystatechange=function() {
           if (xmlhttp.readyState==4) {
                 document.getElementById('result').value = xmlhttp.responseText;
           }
     }

xmlhttp.send(null)
return false;
}

Below is ajaxWork.php which is used in the Javascript above. The code below uses a PHP class called ajax that I defined in ajaxClass.php. The code creates a new instance of the class ajax, reads the parameters from the URL, performs the multiplication, and outputs the result. The results are outputed so that from the response of the XMLHttpRequest, the Javascript can update the example.

Code:
<?php

include("ajaxClass.php");

$objSem = new ajax;
$objSem->readURLParameters();
$objSem->staticExample();

echo $objSem->result;
?>

Below is the ajax class used in the PHP code above. This class is used firstly to read the parameters from the URL (via readURLParameters()) and then to perform the multiplication (via staticExample()) .

Code:
<?php

class ajax {

	var $queryParam = array();
	var $result = 0;
	var $num1 = 0;
	var $num2 = 0;

	function readURLParameters() {
		$qstr = explode("&", $_SERVER['QUERY_STRING']);
		foreach ($qstr as $value) {
			$paramVal = explode("=",$value);
			if (array_key_exists(1,$paramVal)) {
				$this->queryParam[$paramVal[0]] = $paramVal[1];
			}
		}
	}

	function staticExample() {
		if (array_key_exists("num1",$this->queryParam) & array_key_exists("num2",$this->queryParam)) {
			$this->result = $this->queryParam["num1"] * $this->queryParam["num2"];
			$this->num1 = $this->queryParam["num1"];
			$this->num2 = $this->queryParam["num2"];
		}
	}

}
?>

The HTML is even more straightforward (so I won’t bother putting it here). You can download all the files I used here.
Also, be sure to remember the example above will only work in FireFox. To code would be similair to work in IE6, you’d just need to change some of the Javasript. If you have any questions post a comment.

Good luck

Related Articles:

Follow me on Twitter!

Your Ad Here

59 Responses to “How To: Learn AJAX in 20 minutes”

  1. amygdela says:

    Keep up the good work here mate.

  2. Cheech says:

    Wow….thats awesome, i think i get this stuff….Thanx bud

  3. Gerry says:

    Hi just to say your example does work in IE. Well actually it does if you are using IE7 Beta 1 or Beta 2 Preview as these use the native XMLHttpRequest rather than the ActiveX control in previous versions.

    Good example though, perhaps you could go a bit further with the tutorial for us newbies to Ajax.

  4. George A. Papayiannis says:

    @ Gerry

    Thanks, I didn’t know IE7 did. Going further in tutorials for AJAX isn’t a good idea. If you understand the tutorial above in detail, then your best bet (if you’re a PHP person) is to head over to the PEAR HTML_AJAX package (There are other options, but I like the HTML_AJAX direction). There you can begin to use a structured methodology to making AJAX applications.

  5. Pavan says:

    i have a cricket scorecard php file which runs from the database, i want to get the my other Html automatically gets refersh, when that PHP page gets updated.

    pls let me know how to implement the same

  6. Dimitris says:

    Excelent!!! keep up the good work and give us more advices and help. Eyxaristw

  7. navnit says:

    amaging i have learned ajax in only30 minutes.it is surprize for myself.once again thanks.
    please send me some new advice..

  8. George A. Papayiannis says:

    thanks for the kind words..
    until my studies are done, I won’t have time for another tutorial
    after that I will

    Good luck,
    George

  9. socci says:

    Thanks. Can u get us more examples on Ajax?

  10. Surekha.Matte says:

    Really amazing, first I dont know about AJAX. I learned AJAX in 30 minutes greate. Now I have an idea about AJAX. Really thanku so much. Plz give some more examples

  11. vikas says:

    i find it is easy to leanr AJAX .the name given by you “LEARN IN 20 MINUTES” realy works

    thanks

  12. Pavan says:

    Cool one, got to know symantics of AJAX.. and feel of an Ajax application through simple multiplier pgm. Thanks a ton for a smooth introduction.

  13. Goll says:

    muchas gracias! this is a wonderful tutorial :D:D

    I managed to understand the whole thing in less than 20 minutos ;)

  14. raghavendrababugaddam says:

    very very fine to learn basically..but need more explanation if it take more time.
    please go through that

  15. Picknicker says:

    Hi,
    nice work……realy great work :)

    How about you continue with showing an example that shows how to not only read the ‘responseText’ but also how to realy read a specific XML-Field of the response from your HTTPRequest or whatever? Would be much appreciated :)

    greetz

    Picknicker

  16. hello says:

    good but quite complex for non php programmers is there any way for jsp/servlets programmer

  17. Agasthian says:

    good but quite complex for non php programmers is there any way for jsp/servlets programmer

  18. Marnen Laibow-Koser says:

    Just so you know…the example also works in Safari.

  19. Rob C says:

    Works on safari too!@ thanks!

  20. s.shyambabu says:

    Hi :)

    This is very good,each every person easily understand.first besically understand what is ajax and how it is work.
    given example is very good.if any one know little bit of ajax this good.
    am also giving the one example.

    var url=”getStud.php?Rno=”;
    function handleHttpResponse() {

    if (http.readyState==4) {

    result = http.responseText.split(”,”);
    //res=http.responseText;

    document.getElementById(’Name’).value=result[0];
    document.getElementById(’Maths’).value=result[1];
    document.getElementById(’Physics’).value=result[2];
    document.getElementById(’Chemistry’).value=result[3];
    }

    }

    function getStudDetails() {

    var rnoValue = document.getElementById(”Rno”).value;

    http.open(”GET”, url + escape(rnoValue), true);

    http.onreadystatechange = handleHttpResponse;

    http.send(null);

    }

    function getHTTPObject() {

    var xmlhttp;

    try {

    xmlhttp = new ActiveXObject(”Msxml2.XMLHTTP”);

    } catch (e) {

    try {

    xmlhttp = new ActiveXObject(”Microsoft.XMLHTTP”);

    } catch (E) {

    xmlhttp = false;

    }

    }

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

    try {

    xmlhttp = new XMLHttpRequest();

    } catch (e) {

    xmlhttp = false;

    }

    }

    return xmlhttp;

    }

    var http = getHTTPObject(); // We create the HTTP Object*/

    Enter Roll Number:
    Studen Name:
    Maths:
    Physics:
    Chemistry:

    this is a.html file
    then php file

    getStud.php file

    Regards
    S.Shyambabu

  21. s.shyambabu says:

    getStud.php coding

  22. arifshareef says:

    basically the baove program returning the marks but it is not displaying tha marks into the page .\
    it is returning as 50,90,30
    but it is not displaying into three different labels.
    i took div tag also still it is not displaying
    kindly clear the doubt

  23. James says:

    @arifshareef :
    try putting ‘var’ in front of ‘result’

  24. sunil says:

    Thanks….

    I just started learing Ajax… So u can give more advise on how to learn ajax…It is nice one
    to learn… send me more examples…

    Chees.

    Sunil.

  25. Raveesh says:

    I am at the learning stage for AJAX, I am working on ASP, Javascript.
    Is it required to shift to .NET for AJAX implementation.

  26. Manikandan S says:

    its really a good article… keep it up…

  27. Sivagameshwari R K says:

    good one. but, is there any way for JSP programer to grasp from this…?

  28. alexander says:

    It’s interesting topic….but how about using java and JSP also instead php.

  29. Madhan says:

    nice one, just now i started learning ajax,could u able to me wat r all the changes to be done to execute the same code in IE

  30. Tim says:

    Hi,

    I just recently finished writing a very robust simple PHP AJAX toolkit. You can see online examples and example code by visiting my web site

    Thanks for the great article!

    - Tim

  31. Karthik says:

    Good one. As many people asked for how we can use as JAVA developer, pls look at the following link if you want to learn more,
    http://www.w3schools.com/ajax/default.asp

  32. Praveen says:

    Nice one to learn Gr8!!!

  33. fooues says:

    I don’t know how it works very well .. but could you show an example using python + ajax!? …

    thanks all

  34. Michael Temple says:

    Great article. As far as anyone having any problems with different backends, that’s the great thing about AJAX. Alls your server really has to do with the php, jsp pages is actually build the xml document to send back. Hope that helps.

  35. Apurva Vyas says:

    I am apurav vyas i have some proble i submit a form then it not come in same page.For example i fill a form and push a submiit button then it not come in same page i used ajax.I know that it is possible only on ajax but some problem faces that in submit it is not come same page .My problem is related is same any one help me.

  36. pearlkumar says:

    ya its very nice. give some more examples

  37. Rob says:

    Too bad it doesn’t work in IE. On my web site, between 80 to 90% of visitors are IE users (business people). If I ask them to download Firefox to use my site, they’ll move away.

  38. Padmakumar says:

    Very helpfull to undestand its fuctionality……Thank you…..expecting more….

  39. selven says:

    Well done!
    You saved my day.

  40. Navin says:

    Really! It is working. After searching a lot, I found the “Right One”.

  41. Hiroshi says:

    Thanks for good tutorials. This is what i’m looking for it. You help me alot. :)

  42. Madhuri says:

    Hi,
    This example gives an excellent explanation to the beginners. Thank and Thanks a lot…

  43. nguyen ba truong says:

    I’am a Vietnames student. I want to learn about ajax and apply it into my project.
    I feel that is a excited website with many intelligent people.
    Thanks for your comments!

  44. tinhxanh says:

    Too bad it doesn’t work in IE. On my web site, between 80 to 90% of visitors are IE users (business people). If I ask them to download Firefox to use my site, they’ll move away.

    You cant using Ajax in IE if you use exactly HTML syntax.

  45. tinhxanh says:

    You can using Ajax in IE if you use exactly HTML syntax.

  46. DarkDevine says:

    Nice, nice, I understood Ajax =D

    Thanks man, ehm…are there some more examples you can publish? or send by email? would be nice^^

    And…how to code this for IE ?

    lg, dark^^

  47. Murugan says:

    IE7 Beta 1 or Beta 2 users change the code in

    (index.php)

    readURLParameters();
    $objSem->staticExample();

    ?>

    AJAX Example:

    *
    =

    Standard Example:

    num1; ?>> *
    num2; ?>> =
    result; ?>>

  48. Murugan says:

    num1; ?>> *
    num2; ?>> =
    result; ?>>

  49. Hamid says:

    hi
    I am a boy from Iran and I live in a small town
    I read this topic. nice work
    please if you have a complete learning of Ajax send me an email
    our internet is expensive and vrey slow (50 kb per s)
    thanks

  50. kunal karekar says:

    It’s really interesting. I want more information about ajax. if anybody have the notes regarding ajax plz send it to me on kunal.karekar@hotmail.com.

  51. pavan says:

    nice to know something about Ajax

  52. site designer says:

    nice tutorial, i’m still learning the ins and outs of ajax, got to keep up with the times

  53. Subrahmanyam S says:

    it’s very nice, easy time learned…thanks

  54. surabhi says:

    does ajax work only with PHP….cause i donno PHP at all!!!!!!!

  55. Brij Bhushan says:

    Dear Freinds,
    nice work! i adivise , all code must be attached in .zip file so we can just unzip and use code,now i have to copy/ paste above code.it is very boaring.

    rest is good code.

  56. Brij Bhushan says:

    I think we have to add in HTML file following lines…

    Enter Roll #

    Name

    Maths

    Physics

    Chemistry

  57. Brij Bhushan says:

    Enter Roll #
    input name=”Rno” type=”text” id=”Rno” value=”3″>

    Name
    input name=”Name” type=”text” id=”Name” >

    Maths
    input name=”Maths” type=”text” id=”Maths” >

    Physics
    input name=”Physics” type=”text” id=”Physics” >

    Chemistry
    input name=”Chemistry” type=”text” id=”Chemistry” >

    add < before each input tag

  58. bansi says:

    Hi All,
    Learning AJAX is with the above example.
    I suggest all to follow these notes.
    All the Best…

  59. sai Kumar says:

    no need any coach to learn sophasticated technologies,
    the simple examples mentioned above is enough to start learning the such technologies,
    I wish one and all the best…

Leave a Reply

Line and paragraph breaks automatic.
XHTML allowed: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>