Easy Ajax: From Web 1.0 to Web 2.0 in 5 steps

September 30th, 2008  |  Published in Uncategorized

Ajax is a method used to update a page with JavaScript, without reloading the page. This is the basis of all web applications.
ajax in 5 steps
The main ways to update a page are as follows:

  • With an XML HTTP Request
  • Using a hidden Iframe
  • Using a hidden image
  • Using a plain old <script> tag.

In this tutorial we will be using the <script> tag, as it is the easiest, cross browser and is the most logical.

Our aim is to process the user’s data (their name) on the server, without the user having to submit a form and load another page.

Take a look at the View the completed ajax demo if you’re feeling sneaky.

Step 1: Set up the HTML

Our basic HTML is as follows:

<html>
	<body>
		<form name="ajaxform" onsubmit="return doajax()">
			<label>
				What is your name?
				<input type="text" name="yourname" id="yourname">
			</label>
			<input type="submit" value="Submit">
		</form>
		<h2>Results</h2>
		<textarea id="results"></textarea>
	</body>
</html>

(Doctype etc removed here to be concise)

Step 2: Requesting a script

When the form is submitted, we want it to load a server side script and process our data. The doajax() function below will load a server side script (ajax.php) with the contents of the form.

function doajax() {
	// get our data
	var yourname = document.getElementById("yourname").value;
	// create a new script element
	var ajaxscript = document.createElement('script');
	// set the data as a parameter
	ajaxscript.src = 'ajax.php?yourname=' + yourname; to the script's source
	// load the script
	document.getElementsByTagName("head")[0].appendChild(ajaxscript);
	// stop the form from submitting
	return false;
}

Step 3: Processing the data

This is where the clever stuff happens. Normally you’d use the form data, look it up in a database and return a response. We’ll keep this example as simple as possible, so it should be easy to adapt and extend. This code is written in PHP, but you can use any language you want.

This code takes the “yourname” request parameter and converts it to upper case. Of course, this could easily be done with JavaScript, but that’s not the point of this tutorial.

loadResponse('<?php print addslashes(strtoupper($_REQUEST["yourname"])); ?>');

Yes, it’s just 1 line. The PHP here is writing the JavaScript. If you run ajax.php?yourname=Dave it will generate the JavaScript:

loadResponse('DAVE');

The important thing to note is that the server side script is taking in the request parameter, processing it, then writing out some JavaScript.

Step 4: Displaying the data

As you can see form step 3 above, a function loadResponse() is being called by ajax.php. We need to create this function and do something with the data.

function loadResponse(responseString) {
	document.getElementById("results").value = responseString;
}

Step 5: Extend it!

I lied: there are only really 4 steps. This code is very basic and could do with some error checking.

Further ideas to try:

  • Make the JavaScript unobtrusive. The code should check whether the browser supports specific functions and only “ajaxify” the page is it passes. If not, it should gracefully degrade to plain HTML.
  • Implement caching. Store frequent requests in the browser, then load them locally to make it look like your Ajax page is instantaneous.
  • Add onkeyup="doajax()" to the input field. This will send of a request to ajax.php a lot, so is not recommended on its own!
  • Add a timer to the page, so the page is not updated more than once in 200ms
  • After playing with the page a bit you’ll notice there are many script tags. These should be removed.
  • Cheat with a JavaScript library
  • Learn how to do it with XML HTTP Request (post coming soon)

View the completed demo here. Any questions? Comments? Errors?

Leave a Response