AJAX is a neat acronym Asynchronous JavaScript And XML, and a very handy technology.

AJAX is really just a handy shorthand for clever mix of existing technologies that can include HTML, CSS, Javascript XML and/or JSON.

The headline feature of an AJAX is the ability to call data into your web page without having to refresh your page. Key to this is a piece of Javascript functionality originally added by Microsoft for their web based version of Outlook. This feature regales under the somewhat cumbersome name of XMLHttpRequest. As the name implies it is used to request XML via HTTP. It can also be used to request other forms of data, most commonly JSON.

Tip: As the above post discusses we can use jQuery to make AJAX calls but you don’t need jQuery to use AJAX – but as ever it is just sometimes more convenient to use jQuery.

My First XMLHttpRequest

To build our first XMLHttpRequest (XHR) I am going to use a JSON file rather than XML. JSON is Javascript Object Notation and is a way to store data than can be easily manipulated by Javascript. JSON data takes the form of name / value pairs. The name and value are separated by a colon : as follows:

{"Title1": "The Adventures of Oliver Twist"}

Multiple name / value pairs are separated by a comma:

{
  "Title1": "The Adventures of Oliver Twist",
  "Title2": "The Life and Adventures of Nicholas Nickleby",
  "Title3": "The Old Curiosity Shop",
  "Title4": "A Christmas Carol",
  "Title5": "David Copperfield",
  "Title6": "Bleak House",
  "Title7": "A Tale of Two Cities",
  "Title8": "Great Expectations"
}

Our JSON can get way more complicated than this, but this do for starters. In this first example you would need to save the above in a file called ‘dickens.json’. This file would be placed on your web server.

Now lets put together an XMLHttpRequest to use that data in our page. Firstly we create a new XMLHttpRequest object as follows:

var myXHR =new XMLHttpRequest();

We then use the open method of XMLHttpRequest to indicate how we want to request the data and where from. If we wanted to make a GET call for the file ‘dickens.json’ and we wanted the call to be asynchronous we would add the following:

var myXHR=new XMLHttpRequest();
myXHR.open("GET","dickens.json", true);

The third parameter of true makes the HTTP request asynchronous. That is it will send the request to the server for the data in the background allowing the user to continue to interact with the page. As the name implies, with AJAX the vast majority of the time you will leave this argument as true.

Next we’ll add an event handler to be called when the data has loaded. I am going to use the onload event as follows:

var myXHR=new XMLHttpRequest();
myXHR.onload = showData;
myXHR.open("GET","../ajax/dickens.json", true);

My onLoad event is going to call a function called showData so lets add that next.

function showData() {
	// do something
}
var myXHR=new XMLHttpRequest();
myXHR.onload = showData;
myXHR.open("GET","../ajax/dickens.json", true);

Warning: Notice the order of this. The event needs to precede the open method.

We next send the request for the file using the send method.

function showData() {
	// do something
}
var myXHR=new XMLHttpRequest();
myXHR.onload = showData;
myXHR.open("GET","../ajax/dickens.json", true);
myXHR.send(null);

Notice that the send() method has a parameter of ‘null’. This indicates that in this particular case we are not sending data to the server, but as you can probably guess, we can do so if we choose.

Finally lets add some Javascript to the showData() function so we can see if the XHR has been successful. We could use a simple console.info as follows:

function showData() {
	console.info(myXHR.responseText);
}
var myXHR=new XMLHttpRequest();
myXHR.onload = showData;
myXHR.open("GET","../ajax/dickens.json", true);
myXHR.send(null);

… or amend the HTML with getElementById ie:

function showData() {
	document.getElementById('dickens').innerHTML = myXHR.responseText;
}
var myXHR=new XMLHttpRequest();
myXHR.onload = showData;
myXHR.open("GET","../ajax/dickens.json", true);
myXHR.send(null);

In both cases we use the responseText property of the XHR to retrieve the data – in this case the JSON.

Here is the finished example.

There is still lots to do here. For example we would probably want to extract specific values from the JSON rather than display the whole lot. We’ll do that next.

Creating a JSON object

To create a JSON object from the result of the XHR amend the showData function as follows:

function showData() {
    var myJson  = JSON.parse(myXHR.responseText);
    console.dir(myJson);
}

The magic line here is the JSON.parse that converts the string returned by the AJAX call into a JSON object. If you are using the Google Chrome console you will see the output of the console.dir as follows:

You can now see the structure of the JSON object. To extract the value for ‘Title1’ we could use either dot syntax ie myJson.Title1 or array type syntax with square brackets ie myJson['Title1']. Adding the title to the DOM using getElementById we now have:

function showData() {
     var myJson  = JSON.parse(myXHR.responseText);
     document.getElementById('dickens').innerHTML = myJson.Title1;
     //or
     //document.getElementById('dickens').innerHTML = myJson['Title1'];
}

Here is our extended example.

This is just a basic example and there are lots of variants we could have used to achieve the above, so now we’ve got a very simple working example lets next get interactive.

Leave a Comment