Yes, we are in the world of AJAX where we don’t live without jQuery, Prototype or Mootools but when it comes to explaining someone that how raw ajax works, you need an example of plain AJAX which we have been using 5 years back when these libraries were either just born and were not as famous as today. Because my favorite jQuery has become a de facto standard when it comes to DOM manipulation or AJAX.

Recently I have to give an example to one of my friend on how raw AJAX works and here I am sharing that sample with my blog readers as a reference.

Raw AJAX Example:

The Problem Statement: We want to SUM 2 values and we want to achieve that using server-side scripting as we don’t want to do that using JavaScript due to some ABC reason.

The HTML:

Raw AJAX Example Demo

Val 1: 

 + 
Val 2: 


The Javascript:

function doSum()
{
	var url = "simple_ajax_server.php";
	var data = "val1=" + document.getElementById("val1").value + "&val2=" + document.getElementById("val2").value;
	var method = 'POST';
	var async = true;
	var xmlHttpRequst = false;

	// Mozilla/Safari/Non-IE
    if (window.XMLHttpRequest)
	{
        xmlHttpRequst = new XMLHttpRequest();
    }
    // IE
    else if (window.ActiveXObject)
	{
        xmlHttpRequst = new ActiveXObject("Microsoft.XMLHTTP");
    }

	// If AJAX supported
	if(xmlHttpRequst != false)
	{
		// Open Http Request connection
		xmlHttpRequst.open(method, url, async);
		// Set request header (optional if GET method is used)
		xmlHttpRequst.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
		// Callback when ReadyState is changed.
		xmlHttpRequst.onreadystatechange = function()
		{
			if (xmlHttpRequst.readyState == 4)
			{
				document.getElementById("sum").value = xmlHttpRequst.responseText;
			}
		}
		xmlHttpRequst.send(data);
	}
	else
	{
		alert("Please use browser with Ajax support.!");
	}
}

# How does it work?
As you can see in above JavaScript example code that, first we need to initialize XMLHttpRequest object. For IE and non-IE there is a different way to initialize that object. IE being Microsoft product supports XMLHTTPRequest object creation using ActiveX while rest of the browser does it the common way.
If you’re successful creating the HTTP-Request object then you open the connection to URL/URI with which you want to interact to perform desired operation; with method either POST or GET. 3rd optional parameter to open method indicates whether you want to make async request or sync request.
# What is sync / async?
Due to the behavior of JavaScript when you perform any operation in JavaScript statements start executing in parallel. So if you go the async way your next line of code will start getting executed irrespective of whether request is completed or not?
# When to use sync? When you have to perform some operation which is dependent on the result of AJAX request and you can’t define them in request-handler function (one which is defined as onreadystatechange) than you must use sync request.
# When to use async? When you’re loading some static content which is for information purpose and there is no dependent operation to be performed on the data being received from the AJAX request at that time you have to use async.
If you omit that argument it defaults to true meaning an asynchronous request to the server.

# What is readyState?
Here is the list of possible values and meaning of each value of XMLHttpObject’s property readyState, for more reference refer w3.org docs.

0 Uninitialized The initial value.
1 Open The open() method has been successfully called.
2 Sent The UA successfully completed the request, but no data has yet been received.
3 Receiving Immediately before receiving the message body (if any). All HTTP headers have been received.
4 Loaded The data transfer has been completed.

Raw AJAX Example Demo

The PHP/Server-side:

$val1 = (int)$_POST['val1'];
$val2 = (int)$_POST['val2'];

echo $val1 + $val2;

If you can see in open method we are making a post request on simple_ajax_server.php file. In that file we have simply written above content.

See this example live in action.

Generalizing JavaScript: plain_ajax.js

// Common function to initialize XML Http Request object
function getHttpRequestObject()
{
	// Define and initialize as false
	var xmlHttpRequst = false;

	// Mozilla/Safari/Non-IE
    if (window.XMLHttpRequest)
	{
        xmlHttpRequst = new XMLHttpRequest();
    }
    // IE
    else if (window.ActiveXObject)
	{
        xmlHttpRequst = new ActiveXObject("Microsoft.XMLHTTP");
    }
	return xmlHttpRequst;
}

// Does the AJAX call to URL specific with rest of the parameters
function doAjax(url, method, async, responseHandler, data)
{
	// Set the variables
	url = url || "";
	method = method || "GET";
	async = async || true;
	data = data || null;

	if(url == "")
	{
		alert("URL can not be null/blank");
		return false;
	}
	var xmlHttpRequst = getHttpRequestObject();

	// If AJAX supported
	if(xmlHttpRequst != false)
	{
		// Open Http Request connection
		if(method == "GET")
		{
			url = url + "?" + data;
			data = null;
		}
		xmlHttpRequst.open(method, url, async);
		// Set request header (optional if GET method is used)
		if(method == "POST")
		{
			xmlHttpRequst.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
		}
		// Assign (or define) response-handler/callback when ReadyState is changed.
		xmlHttpRequst.onreadystatechange = responseHandler;
		// Send data
		xmlHttpRequst.send(data);
	}
	else
	{
		alert("Please use browser with Ajax support.!");
	}
}

# Same JavaScript can be generalized and written in following way: (embed in html)

# How to use?: (include plain_ajax.js first and then embed following code;)

var displaySum = function()
{
	if (this.readyState == 4)
	{
		document.getElementById("sum").value = this.responseText;
	}
}

function doSum()
{
	var url = "simple_ajax_server.php";
	var data = "val1=" + document.getElementById("val1").value + "&val2=" + document.getElementById("val2").value;
	var method = 'GET';
	var async = true;
	doAjax(url, method, async, displaySum, data);
}

Example can be downloaded here or find it in my gist repository.