Simple AJAX

June 24, 2008 | AJAX | 0 comments

I’ve been teaching myself AJAX over the last month or so. I’ve written a simple version of the ever popular Autocomplete field but for now I want to give a quick example of what AJAX is and how it can be used simply and implemented quickly.

What is AJAX?
The acronym if I remember correctly stands for Asynchronous Javascript And XML but i’m likely to be wrong šŸ™‚

What you do need to know is that it uses Javascript to fire off custom requests wherever you want without having to reload the page. I have already mentionned the Autocomplete example above so I’ll use that as an example. At work we use something similar for a UK town search. A user starts to type in the name of a town and after a couple of keystrokes a list of suggestions appears.

Now for the technical bit…
In the above example, when the input field gets to a pre-determined number of characters the Javascript sends an asynchronous request to the server then does nothing. It does nothing because of course its asynchronous! The beauty of this is that the client machine doesn’t have to wait for a response so if a response comes then something will happen otherwise it fails seamlessly.

Putting this back into the example I gave, If the server returns something then the list of suggestions pops up or refreshes with the new data, otherwise it just wont do anything.

A callback function is declared and sent to the server as part of the request. If a number of conditions are met (ie: the server url is valid and it’s set up to receive such requests) then if the server echos anything it will be passed to the callback function. The callback then runs whatever code you have written and does what it wants with the returned result. This is better explained in some code so let’s see how it all works!

This script to use a remote server to echo a random number is the simplest thing i could think of:

<script>

function ajax_request() {
	var request = false;

	if (navigator.appName == "Microsoft Internet Explorer") {
		request = new ActiveXObject("Microsoft.XMLHTTP");
	} else {
		request = new XMLHttpRequest();
	}

	request.abort();
	request.open("GET", "ajax.php", true);
	request.onreadystatechange=function() {

		if(request.readyState == 4) {
			alert(request.responseText);
		}
	}
	request.send(null);
}
</script>

Ill take you through it section by section…

First we need to create an AJAX request object, this is done is every proper browser using

request = new XMLHttpRequest();

Of course Microsoft have to be different and don’t support this call (at the time of this post) so we have to put in the nasty if statement that calls this code

request = new ActiveXObject("Microsoft.XMLHTTP");

Next we actually have to set up the request, ie: tell it where to call and what callback function to run

request.open("GET", "ajax.php", true);
request.onreadystatechange=function() { }

In this example we are telling it to call ajax.php using GET (POST is also an option) and to alert the response as the callback (alert(request.responseText);).
Finally we need to fire off the request using

request.send(null);

There are a few bits i’ve missed out for the time being, namely

if(request.readyState == 4) {

}

This readyState option is checked in the callback and only does anything when it isĀ  set to 4. This is the stage when a script actually does something. There are several other requests which i’m sure you can research but for the basic script, just leave the IF statement in. I also haven’t mentionned the XML side of things but we will leave that for another day.

The code that responds to all of this is a simple PHP script. It can simply echo out its data to be picked up by the callback as follows

<?php
echo rand(1,99);
?>

So that’s really it in terms of getting a basic example going but if you consider the possibilities of something rooted in something so simple then you will soon begin to see where you can easily place it into your script.

For example, the posting section in wordpress uses AJAX for an autosave feature in the post window. It probably has a bit of JS on a timer loop that takes the contents of the ‘Post’ box and sends it to a script which updates a DB table and then returns the flag to say whether it saved properly or not. See! easy and very functional!

Alternatively if you like the idea of AJAX but can’t be bothered to play with the proper stuff then there’s always JQuery and Scriptaculous

A Donate Button!

0 Comments

Trackbacks/Pingbacks

  1. SACK of AJAX | Sean Barton's Blog - [...] those of you that don’t know what AJAX is, please read my simple tutorial here. For those of you…

Leave a Reply

Divi United

About this site and Sean Barton

Picture of Sean
Sean Barton is a Freelance PHP Website Developer in Crewe, Cheshire. He is a Wordpress and CMS/Framework specialist.
This site was set up in 2008 as a tutorial and scripting resource for the PHP language and Wordpress.
Find out more about Sean on the About Me page or use the Hire Me page to get in touch. For more information about Sean's work take a look at the Portfolio

Our Services

  • Wordpress plugin/theme development
  • Divi specialist
  • Ecommerce (Woocommerce, WPSC, Shopify, Magento)
  • PSD to Wordpress theme conversion (Responsive)
  • Website design work (Banners, Logos, Full Site, etc)
  • Website analysis (security, usability, SEO)
  • API Integrations (InfusionSoft, SalesForce, Ontraport, Customer Thermometer, etc..)
  • Wordpress consultancy & expert advice
  • Crisis support
  • Website hosting

The main services offered are Wordpress based although we do a great deal of technical programming for bespoke systems. From troubleshooting, extending frameworks, finding bugs to writing them from scratch.

Find out more by looking through our past projects or get a quote.

Be the first to hear about new products/updates!

This is a mailing list for those people interested in being toldĀ when we releaseĀ a new product (Divi plugin or Theme).

We shall also use this list to let you know about product updates and releases.

You have Successfully Subscribed!