Ajax Hello World Example

Ajax Hello World is the first lesson in a series regarding Ajax tutorials with examples. We will cover from technicalities and basics to advanced and concrete examples/scenarios.

What is Ajax?

Ever been to a website, logged on or added something to cart and the action happened without page reload? That is Ajax!

Ajax is a technology that allows sending and receiving data using the HTTP protocol. Data transfer is done in the background, asynchronously and this whole process is managed client side, by the browser.

How Ajax works?

In order to create an ajax application you need:

  • A server with a script running (php, java, pythong etc). Basically a link that can be used to issue a GET or POST request and which returns back some data.
    ie: http://localhost/myInfo.php
  • HTML page with javascript code that issues GET or POST requests using Ajax.

In a nutshell, to have an ajax setup you need an ordinary server side script that returns data (based on queries etc) and a client side script that uses the XMLHttpRequest object to send requests to that script. This object is also capable of reading the response, thus completing the lifecycle.

XMLHttpRequest is a built in object (into javascript) supported by all major browsers. So nothing to download or setup. It’s already there.

Setup

For this tutorial I will use php as a server side language because it’s easier to setup and work with. If you are more comfortable with other server side language you can use that. As long as you can create the same operations in your language all examples should work.

Ajax Hello World example

Create a file called greeting.php and place it inside your Apache‘s htdocs folder.

Write the following in it:

<?php
	header('Content-Type: text/xml');
	echo '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>';
	echo '<response>';
	$name = $_GET['name'];
	echo 'Hello ' . $name . '!';
	echo '</response>'
?>

What happened?

  1. We set the response content type to text/xml. Put http://localhost/greeting.php?name=superglobals in your address bar and see the browser showing an xml file.
  2. We use echo statements to create the xml file aka write to the output.
  3. We get the param name‘s value by using $_GET[‘name’] and store it’s value (superglobals) in the $name variable.
  4. We write it back and close the xml response tag.

Create an html file and place it inside the same folder as greeting.php. Call it whatever you want. Mine is called index2.html.

<html>
	<head>
		<title>Ajax Hello World</title>
	</head>
	<script>
		
	</script>
	<body>
		Please enter your name:
		<input type="text" id="name" />
		<input type="button" value="OK" onclick="sendName();" />
                <div id="serverResponse" style="color: red"></div>
	<body>
</html>

Place these inside the <script></script> tag:

function sendName() {
	/* if very old IE such as IE6 */
	if (window.activeXObject) {
		request = new ActiveXObject("Microsoft.XMLHTTP")
	} else {
		/* for any other modern browser (ie included) */
		request = new XMLHttpRequest();
	}
	
	/* if state = not initialized or state complete */
	if (request.readyState == 4 || request.readyState == 0) {
		var name = encodeURIComponent(document.getElementById("name").value);
		/* specify the type of request */
		request.open("GET", "greeting.php?name=" + name, true);
		/* on readystatechange is triggered everytime state is changed */
		request.onreadystatechange = processResponse;
		request.send(null); //null because we already specified param above ("greeting.php?name=")
	}
}
		
function processResponse() {
	/* is state complete */
	if (request.readyState == 4) {
		/* if response status == OK */
		if (request.status == 200) {
			/* get response data as XML */
			var response = request.responseXML;
			var documentElement = response.documentElement;
			var serverText = documentElement.firstChild.data;
			document.getElementById("serverResponse").innerHTML = serverText;
		}
	}
}

Go to http://localhost/index2.html and write something in the textbox. Click ‘OK’. It should look like this:

ajax hello world example

If you open Developer Tools in Chrome (F12) and go to the Network tab > XHR you can see the request made by the browser and the response:

ajax hello world example browser

FacebookTwitterLinkedin