How To Create A Simple AJAX Request

The creation of an AJAX request can be divided into four steps:

  1. Create an XMLHttpRequest Object
  2. Create a callback function
  3. Open the request
  4. Send the request

Let’s say we have an index.html file as follows:

<!DOCTYPE html>
<html>
<head>
	<title></title>
</head>
<body>
	<button id="load" onclick="send_AJAX()">Bring it!</button>
	<div id="ajax">
		
	</div>
</body>
</html>

It currently does nothing, except displaying a button on the page. That button triggers the function send_AJAX() but it isn’t defined so let’s define it now!

<!DOCTYPE html>
<html>
<head>
	<title></title>
	<script>
		var xhr = new XMLHttpRequest();
		xhr.onreadystatechange = function() {
			if ( xhr.readyState == 4 ) {
				document.getElementById('ajax').innerHTML = xhr.responseText;
			}
		};
		xhr.open( 'GET', 'mars.html' );

		function sendAJAX() {
			xhr.send();
			document.getElementById('load').style.display = "none";
		}
	</script>
</head>
<body>
	<button id="load" onclick="sendAJAX()">Bring it!</button>
	<div id="ajax">
		
	</div>
</body>
</html>

Lines 6-17 are important here. Let’s look at it step by step:

  1. Create an XMLHttpRequest Object
var xhr = new XMLHttpRequest();

2. Create a callback function

xhr.onreadystatechange = function() {
	if ( xhr.readyState == 4 ) {
		document.getElementById('ajax').innerHTML = xhr.responseText;
	}
};

We create a callback function which checks whether the readyState is 4 (i.e. whether it is done). I

f so, get the element with “load” id and set its innerHTML with the response text.

3. Open the request

xhr.open( 'GET', 'mars.html' );

This opens a GET request to the mars.html file in the same directory as index.html.

4. Send the request

function sendAJAX() {
	xhr.send();
	document.getElementById('load').style.display = "none";
}

It sends the request and then hides the button.

The end result? Whatever was inside mars.html would be fetched asynchronously and the element with ajax id would be populated with that data.

Note

If it doesn’t work, check your browser’s console. You might see a Cross-Origin Request Blocked error.

If you see it, run a local server and then try loading these files via the server.

For example: Instead of loading the file via file:///Users/omkar/Desktop/index.html, I moved it inside a folder called “test” and moved that folder into my local VVV WordPress dev environment.

After starting VVV, I could load the file via http://one.wordpress.test/test/ as follows:

This is a very basic example of how a simple AJAX request can be created to load things asynchronously.