Tips and Tricks on Web and Technology

A simple AJAX tutorial

AJAX powered webpages have an edge when response time and resource usage is the matter of concern. AJAX shows quick results within a blink of an eye. And the best part is user never gets to see the whole page refreshed again for simple responses.

Create a PHP file and save in the same directory where ajax.html is placed. Name this PHP script script.php (if you change the name you’ll have to change it in the submitForm function also)

<?php
$fruits = Array(1=>"Apple", 2=>"Banan", 3=>"Orange");
if(isset($_REQUEST['fruit']))
echo $fruits[$_REQUEST['fruit']];
else
echo "Sorry";
?>
Note: I have used an anonymous function in onreadystatechange event and created my xmlhttp object local (not global).
This is relly important as you might have problems in case you have made multiple calls to the same ajax file from a single HTML page.