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 |
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 |
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><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");</em></span><span style="color: #333399;"><em>af1.showprogressbar=false;</em></span><span style="color: #333399;"><em>ti1.start();'> <div><span>Your dynamic content is: </span><span id="ID1">First</span></div> </body></html></em></span> |