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.

var af1=new ajaxObject(“ajax.php”,”ID1″);

This has been already discussed in my previous article.

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

var ti1=new timerObject(5000,function () {af1.update(“t=3”);});

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:

ti1.start();

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

<body onload=’ti1.start();’>

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:

<body onload=’af1.update(“t=3”);af1.showprogressbar=false;ti1.start();’>

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:

<html>
<head>
<script src=”ajax.js”  type=”text/javascript”></script>
<script type=”text/javascript” >
var af1=new ajaxObject(“ajax.php”,”ID1″);
var ti1=new timerObject(5000,function () {af1.update(“t=3”);});
</script>
</head>
<body onload=’af1.update(“t=3”);
af1.showprogressbar=false;ti1.start();’>
<div><span>Your dynamic content is: </span><span id=”ID1″>First</span></div>
</body></html>

Lascia un commento

Il tuo indirizzo email non sarà pubblicato. I campi obbligatori sono contrassegnati *

ERROR: si-captcha.php plugin: GD image support not detected in PHP!

Contact your web host and ask them to enable GD image support for PHP.

ERROR: si-captcha.php plugin: imagepng function not detected in PHP!

Contact your web host and ask them to enable imagepng for PHP.

Questo sito usa Akismet per ridurre lo spam. Scopri come i tuoi dati vengono elaborati.