Ajax tutorial - dynamic content

Introduction

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">
<html>
<head>
  <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>
</head>
<body>  
  
</body>  
</html>

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];
  return;
}

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:

dynamicContent_ajaxObjects[ajaxIndex].runAjax();

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];
    return;
  }
  
  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); };  

  dynamicContent_ajaxObjects[ajaxIndex].runAJAX();  
  
  
}

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 =
  dynamicContent_ajaxObjects[ajaxIndex].response;

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

if(enableCache){
  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 =
    dynamicContent_ajaxObjects[ajaxIndex].response;
  if(enableCache){
    jsCache[pathToFile] =
    dynamicContent_ajaxObjects[ajaxIndex].response;
  }
  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.

Comments

Tom Walsh
Doesn't work only displays Loading Content....
Tom Walsh at 05:47PM, 2011/03/03.
Jan Kreps
Works for me. Thanks for this tutorial, finally I was able to catch the sack properly.
Jan Kreps at 09:50AM, 2011/03/17.
Admin comment
DHTMLGoodies
Jan,It has been some time since I created this tutorial. Today, I will probably recommend that you try out a library like Mootools and the Ajax from there. They got a very smooth way of doing this.Here's a small example for your: Let's say you want to load content from an external file and put it inside this div:<div id="dynamicContent"></div>All you have to do with mootols is to add a line like this:$('dynamicContent').load('externalfile.html');
DHTMLGoodies at 11:30AM, 2011/03/17.
Jan Kreps
Thanks for your advice, but I need it for some dokuwiki plugin and dokuwiki uses sack. So I should stick to it :-)But surely I will try Mootools for some other project.
Jan Kreps at 02:25PM, 2011/03/17.
Julian
is not working with google chromeLoading content...
Julian at 02:36PM, 2011/03/30.
Pritee Sharma
Its working fine with all browser. Even in IE9 and Google chrome :)
Pritee Sharma at 06:54AM, 2011/04/14.
Manoj
I didnt get the js/ajax.js file .... help me to down load that plssss
Manoj at 05:35AM, 2011/05/11.
Admin comment
DHTMLGoodies
Monoj,ajax.js can be found here: http://www.dhtmlgoodies.com/AJAX/ajax.js
DHTMLGoodies at 09:41AM, 2011/05/11.
Will
what a Bummer...does not work with Chrome :(
Will at 01:28AM, 2011/06/04.
Ashish
Hi, It does not works with Mozilla Firfox. Explain me solution
Ashish at 06:51AM, 2011/09/14.
TomBr
Hi, I've used this SACK before to populate dropdowns, but now I face a strange issue.The sack component always returns the results from the previous time.So the very first time I change the parent dropdown, I get no results in the child dropdown. The second time I change the parent dropdown (choose other value), the child dropdown is populated with the results of the first time ..and so on.any ideas?I've cleared cache etc..
TomBr at 02:34PM, 2011/10/13.
Steve
This has been an essential tool in my programming kit - thank you for making my life so much easier!!! Is there a way of targeting a div in another frame? The page calling the ajax is in an iframe and I want to affect content in it's parent page.
Steve at 02:47PM, 2012/03/27.
Alex
Great tutorial. I'd like to know where to take this though. Is this a popular method? WHat if you only want to take a part of testFile? Not ALL of the content?
Alex at 04:23PM, 2012/05/05.
Ivan
I have wrong charset in loadet file. The file which I load throw ajay is in the right charset , but when displays on page it has wrong charset.LP I.
Ivan at 01:40PM, 2013/03/31.
Chris Newbie
I knwo this is old, but I am new to all this, I was wondering if anyone had a example of how display only certain parts of a html using the div tags, and ajax.Thanks in advance for your help.
Chris Newbie at 06:28PM, 2013/05/07.

Post your comment

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

Confirmation code:

Advertisement:
LudoJS framework
dhtmlchess.com
Go to cbolson.com


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