Home

AJAX - Asynchronous Java and XML

AJAX is not a language unto itself. It uses JavaScript to perform asynchronous transfers to the server so that a web page can respond to user actions in real-time, send data to and receive data from the web server, and update the web page in response to user activity without reloading.

In Internet Explorer this is made possible through the ActiveXObject object. In all other standards compliant browsers, the XMLHttpRequest is used.

Example Code

The following demonstrates how to send to and receive a response back from the server using these objects.

function fetchData(url, dataToSend, objectID)
{
	var pageRequest = false;
	if(window.XMLHttpRequest) pageRequest = new XMLHttpRequest();
	else if(window.ActiveXObject) pageRequest = new ActiveXObject("Microsoft.XMLHTTP");
	else return false;
	pageRequest.onreadystatechange = function()
	{
		filterData(pageRequest, objectID);
	}
	if(dataToSend)
	{
		var sendData = 'sendData=' + dataToSend;
		pageRequest.open('POST', url, true);
		pageRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
		pageRequest.send(sendData);
	}
	else
	{
		pageRequest.open('GET', url, true);
		pageRequest.send(null);
	}
}

The following demonstrates how to filter received data.

function filterData(pageRequest, objectID)
{
	var object = document.getElementById(objectID);
	if(pageRequest.readyState == 0)
		object.innerHTML = '<h3>Fetching Data... </h3>';
	if(pageRequest.readyState == 1)
		object.innerHTML = '<h3>Loading Data... </h3>';
	if(pageRequest.readyState == 2)
		object.innerHTML = '<h3>Data Loaded... </h3>';
	if(pageRequest.readyStata == 3)
		object.innerHTML = '<h3>Data Ready!</h3>';
	if(pageRequest.readyState == 4)
	{
		if(pageRequest.status == 200) object.innerHTML = pageRequest.responseText;
		else if (pageRequest.status == 404) object.innerHTML += 'Sorry, that page is gone.';
		else object.innerHTML = 'Sorry, something unidentifiable is borked.';
	}
}

The arguments here, pageRequest is an instantiation of the object used in the previous example, either a "XMLHttpRequest" object or in the case of Explorer, an "ActiveXObject" object.

The second argument is the object on the webpage to place the data in. Typically, at the spot on the webpage where you want the data to appear, you'd put HTML code like this:

<div>&nbsp;</div>
Google Ad Filler