Javascript

Simple Ajax Tutorial

ajax

Ajax is at the heart of Web2.0 design it is used across the most popular websites from Facebook to Twitter. What is Ajax? It is a method of a web page making a request to another file or program to obtain data and then to dynamically show that data without reloading the page.

There are lots of Ajax libraries available, most of which claim they are easy to setup and understand but I find that incorrect in most instances as their API is fairly bloated and one can find it difficult to grasp what is the real Ajax part and the rest of the bloated API part. So here I will attempt to explain just the most basic fundamental aspect of Ajax.

Ajax uses just a few lines of JavaScript to request another page similar to how a form would access another page using either GET or POST method. However it is not necessary to send any GET or POST data unless the page that is being accessed is in itself dynamic responding to the GET or POST method request data fields. In this example we will ignore sending any data and forget about the page we are calling being any type of PHP, Perl, ASP, CGI dynamic page, we will simply request a regular text file.

The comments in the below code should tell you everything you need to know. I’ve stripped the entire Ajax process down to its most basic elements so you can look at the code and see what it is with no extra baggage that can me it confusing.

File: blurb.txt (make this file and safe it to your webserver)

My voice is my password, verify.

File: ajax.html (make this file and save it to your webserver)

<html>
<head>
<title>Simple Ajax Example</title>

<script language="Javascript">
function simpleAjax()
	{
	var xmlhttp = new XMLHttpRequest(); // The XMLhttpRequest is the built object that actually dos the Ajax call
	xmlhttp.onreadystatechange = function () // this function is what will be called AFTER the requested page has been fetched
		{
		if (xmlhttp.readyState == 4 && xmlhttp.status == 200) // verifies the status of the fetched page to be OK
			{
				var x = xmlhttp.responseText; // Get the results of the fetched page and put in the variable "x"
				document.getElementById("data").innerHTML = x; // change the contents of DIV with id "data" to the value of "x"
			}
		}
	xmlhttp.open("GET", "blurb.txt", true); // the page request to make, using method GET (could be POST) and is located in the same dir path as calling file
	xmlhttp.send(); // send the request which then calls the above function to process the results
	}
</script>

</head>
<body>

<a href="" onclick="simpleAjax();return false;">Click Here for Ajax</a>

<div id="data">
	What is your Password?
</data>

</body>
</html>

Goto http://(yourdomain)/ajax.html and click on “Click Here for Ajax”. You should see the text in the DIV with id=”data” change. That is all Ajax is.