ajaxObject tips: periodic update of contents

One of the possibles use of ajax technology is to have an automatic update of data in a web page.This is easily possible using the ajaxObject.

First of all, we have to think to an object that is available in the ajaxObject: timerObject.

This is normally used inside ajaxObject for timeout and progress bar, but it can also be used any time a timer is needed.

So, what code to do this?

Firstly let define a new ajaxObject to prepare a request for content.

1
<p style="text-align: justify;"><span style="color: #333399;"><em>var af1=new ajaxObject("ajax.php","ID1");</em></span></p>

This has been already discussed in my previous article.

Then we have to create a new timer that will make the request:

1
<p style="text-align: justify;"><em><span style="color: #333399;">var ti1=new timerObject(5000,function () {af1.update("t=3");});</span></em></p>

The three parameters of timeObject call are:

1. Timing in milliseconds.

2. Function to be executed, in this case is an ajax request

The third optional parameter would be the ID of <span> or <div> where to show a progress bar, but this is not needed since the progress bar will be displayed by the ajaxObject.

Finally we have to activate the timing. This can be done calling:

1
<p style="text-align: justify;"><span style="color: #333399;"><em>ti1.start();</em></span></p>

that can be placed were you need. For example using onload:

1
<p style="text-align: justify;"><span style="color: #333399;"><em>&lt;body onload='ti1.start();'&gt;</em></span></p>

This will do the job. Of course, the first call will be done after the timeout expires (in our example 5 seconds) and you might dislike a similar behavior and you might want the first call to be done just after loading the page. If so, just change the body call in the following way:

1
<p style="text-align: justify;"><span style="color: #333399;"><em>&lt;body onload='af1.update("t=3");af1.showprogressbar=false;ti1.start();'&gt;</em></span></p>

The code af1.showprogressbar=false; just disable the progress bar, so old content remains until a new one is available.

That’s all folks!

Here is the full HTML code:

1
2
3
4
5
6
7
8
9
10
11
<span style="color: #333399;"><em>&lt;html&gt;
&lt;head&gt;
&lt;script src="ajax.js"  type="text/javascript"&gt;&lt;/script&gt;
&lt;script type="text/javascript" &gt;
var af1=new ajaxObject("ajax.php","ID1");
var ti1=new timerObject(5000,function () {af1.update("t=3");});
&lt;/script&gt;
&lt;/head&gt;
&lt;body onload='af1.update("t=3");</em></span><span style="color: #333399;"><em>af1.showprogressbar=false;</em></span><span style="color: #333399;"><em>ti1.start();'&gt;
&lt;div&gt;&lt;span&gt;Your dynamic content is: &lt;/span&gt;&lt;span id="ID1"&gt;First&lt;/span&gt;&lt;/div&gt;
&lt;/body&gt;&lt;/html&gt;</em></span>
image_print