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.
[cc lang=”javascript”]
var af1=new ajaxObject(“ajax.php”,”ID1″);
[/cc]
This has been already discussed in my previous article.
Then we have to create a new timer that will make the request:
[cc lang=”javascript”]
var ti1=new timerObject(5000,function () {af1.update(“t=3”);});
[/cc]
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:
[cc lang=”javascript”]
ti1.start();
[/cc]
that can be placed were you need. For example using onload:
[cc lang=”html”]
<body onload=’ti1.start();’>
[/cc]
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:
[cc lang=”html”]
<body onload=’af1.update(“t=3”);af1.showprogressbar=false;ti1.start();’>
[/cc]
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:
[cc lang=”html”]
<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>
[/cc]