Ajax tutorial - dynamic content


Ajax is a great tool to create more dynamic web pages and enhance user interaction. With Ajax, we can contact our server from our Javascript code and get data from the server without having to reload the page.

In this tutorial, we will see how to use Ajax in your Javascript code. We will create a "dynamic content" script like the one you can download from the Ajax section on this site.

We will use the SACK library in this script. You can download it from here.

Ps! This page is print friendly. Send it to a printer if you like to look at it on paper.

Let's start

What we are going to create is a script that uses Ajax to populate DIV tags on our page with content from external files.

The first thing we do is to create an empty html file. We will call it ajax-dynamic-content.html.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
  <title>Ajax dynamic content</title>
  <script type="text/javascript" src="js/ajax-dynamic-content.js"></script>
  <script type="text/javascript" src="js/ajax.js"></script>

Notice that we refer to two Javascript files: js/ajax.js which is the library from twilightuniverse and js/ajax-dynamic-content.js which is a file we're going to create in this tutorial.

We also need a couple of <DIV> tags on our page(A <DIV> tag is a block level element without any default styling). We put them in between <BODY> and </BODY>.

<DIV id="content_one"></DIV>
<DIV id="content_two"></DIV>

We identify them as "content_one" and "content_two". We give them Id's in order to refer to them dynamically by our Javascript code.

Javascript code

Global variables

Now, we start working with our ajax-dynamic-content.js file. We start with a blank file.

The first thing we need to do is to declare a global variable for the Ajax(sack) objects. The ajax.js file contains a class called "sack".

We could create a variable like this:

var ajaxObj = new sack(); // Don't create it like this

I.e. a single Ajax/sack object. The only problem with this is that we can't work with more than one ajax request simultaneously(since we only have one sack object). If we want to popuplate a lot of divs on our page, we have to wait until the first one is populated before we popuplate the second one. That's not something we want.

To solve this, we create an empty array. This will make it possible to create an array of sack/Ajax objects.

var dynamicContent_ajaxObjects = new Array();

It would also be useful to have some cache functionality. This means that if more than one div is popuplated from the same file, we could display content from our JS cache instead of sending another Ajax request to the server. For this, we need another array for our cached content, and perhaps a third variable indicating if cache is enabled or not(In some cases, it could be useful to disable cache).

var jsCache = new Array();
var enableCache = true;

These 3 variables is declared at the top of our ajax-dynamic-content.js file.

ajax_loadContent function

We will now start working on our main function which we call ajax_loadContent. This is the function we will call from our HTML file when we want to popuplate divs on our page. This function takes two arguments

  1. The id of the <DIV> tag(s) on our page,
  2. The path to the file on the server which will populate the DIV.

function ajax_loadContent(divId,pathToFile)


The purpose of this function is

  • To populate the divs from cache if cache is enabled and this specific content is cached.
  • Create an Ajax/sack object and send a request to the server if content isn't cached or cache is disabled.

Cache is stored in the javascript array jsCache. At the top of the ajax_loadContent function we will check if cache is enabled and if the content of the given url is in the cache:

if(enableCache && jsCache[pathToFile]){


jsCache is an associative array where the key is the path to the files. If the test above evaluates to true, we will populate our div with content from this jsCache array:

if(enableCache && jsCache[pathToFile]){
  document.getElementById(divId).innerHTML = jsCache[pathToFile];

Now, we need to use Ajax to get content from the server if there isn't anything in the cache or cache is disabled. To do this we create a sack object. As mentioned before, we have a global Javascript array for these objects. The first thing we do is to get the index of our new array element:

var ajaxIndex = dynamicContent_ajaxObjects.length;

Next, we show a temporary message in our div:

document.getElementById(divId).innerHTML = 'Loading content...';

This message will show inside the div until content from the external file is loaded.

The sack class

There is one variable/property of the sack object which we always will define:

  • requestFile

We update this variable with the path of our external file.

We also have some useful methods. These are:

  • onLoading = What to do when Ajax starts sending the request
  • onLoaded = What to do when Ajax is finished sending the request
  • onInteractive = What to do when Ajax is waiting for response.
  • onCompletion = what to do when ajax is finished with it's request

These methods refers to the readyState property of the XMLHTTP object. The readyState property indicates the status of the request(is it sending data, is it waiting for data etc.). The codes are:

  • 0 = uninitialized
  • 1 = loading(onLoading method)
  • 2 = loaded(onLoaded method)
  • 3 = interactive(onInteractive method)
  • 4 = complete(onCompletion method)

The most important method is onCompletion. It defines what we want to happen when Ajax is finished(i.e. after data sent and response received).

We will now create a sack object, define the property requestFile and an onCompletion method:

Create a sack object:>

dynamicContent_ajaxObjects[ajaxIndex] = new sack();

Define requestFile:

dynamicContent_ajaxObjects[ajaxIndex].requestFile = pathToFile;

Define onCompletion method:

dynamicContent_ajaxObjects[ajaxIndex].onCompletion =
function(){ ajax_showContent(divId,ajaxIndex,pathToFile); };

We have defined onCompletion as a dynamic function. When the Ajax request is completed, it will call a function named ajax_showContent. We need to create this function in order to show the response from Ajax inside our div.

This function will have 3 arguments:

  1. divId = The div id we are working with
  2. ajaxIndex = The index of our current sack() object(i.e. array index)
  3. pathToFile = Path to the file. We need this in order to update our Javascript cache

Before we look at the ajax_showContent function, let's finish the ajax_loadContent function. The only thing missing is to execute the Ajax call. This is done with use of the runAJAX method:


Now, we have a ajax_loadContent function which looks like this:

function ajax_loadContent(divId,pathToFile)
  if(enableCache && jsCache[pathToFile]){
    document.getElementById(divId).innerHTML = jsCache[pathToFile];
  var ajaxIndex = dynamicContent_ajaxObjects.length;
  document.getElementById(divId).innerHTML = 'Loading content...';
  dynamicContent_ajaxObjects[ajaxIndex] = new sack();
  dynamicContent_ajaxObjects[ajaxIndex].requestFile = pathToFile;

  dynamicContent_ajaxObjects[ajaxIndex].onCompletion =
  function(){ ajax_showContent(divId,ajaxIndex,pathToFile); };  


The ajax_showContent function

This is the function that would be executed by our Ajax objects when it is finished returning content from the server. The purpose of this function is to put content into our divs and to update our Javascript cache array.

We start with an empty function like this:

function ajax_showContent(divId,ajaxIndex,pathToFile)


The first we do inside this function is to populate our div:

The data from the external file is saved in a property of the sack object. The name of this property is response. So the code for populating the div is:

document.getElementById(divId).innerHTML =

We also want to update our cache array if cache is enabled. This is done with the following code:

  jsCache[pathToFile] = dynamicContent_ajaxObjects[ajaxIndex].response;

It's very simply code. We just adds a new element to our associative array. If an other div is also popuplated from the same external file, our script will get content from this JS array instead of contacting the server. This will save some time and bandwidth.

The last line of code inside ajax_showContent is just a line that clears the current index from our array of ajax objects. We don't need to save the object in the memory when it's finished with it's job.

dynamicContent_ajaxObjects[ajaxIndex] = false;

You should now have a function like this:

function ajax_showContent(divId,ajaxIndex,pathToFile)
  document.getElementById(divId).innerHTML =
    jsCache[pathToFile] =
  dynamicContent_ajaxObjects[ajaxIndex] = false;

Summary of ajax-load-content.js

That's it. We're finished with our ajax-dynamic-content.js file. We have created 3 global variables and two Javascript functions. The ajax_loadContent function is our main Javascript function which we will call from our HTML file in order to populate divs. The ajax_showContent function is a function called by our Ajax object when data is returned from the server.

Call the script from the HTML file

Now, we want to populate our two divs from our HTML file. We do that by inserting two lines of Javascript code at the bottom of the file(right above </BODY>).

<SCRIPT type="text/javascript">
ajax_loadContent('content_one','external/testFile_1.html'); ajax_loadContent('content_two','external/testFile_2.html'); </SCRIPT>

The divs will now be populated with the content of the external files external/testFile_1.html and external_testFile_2.html(You will need to create this files)

Download the script

You can download the script we have created in this tutorial from this Zip file. You can also take a look at the result here.


No one has commented this - be first!

Post your comment

Don't have an avatar? Create one at Gravatar.com.

Confirmation code:

LudoJS framework
Go to cbolson.com

About/Contact | A good idea? | Submit a script | Privacy notice
© 2005 - 2024 dhtmlgoodies.com