Monitoring device status with help of AJAX
This article is not AJAX tutorial, this is live, functional example of using AJAX technology in production firm intranet. In text you can find code samples and some comments about this technology using. To the study in depth I recommend set of articles Mastering Ajax on IBM developerworks server.
Example comes from intranet application melting glass, which was running since 2001 year. In schematic picture of glass tank are placed cells (frames) for real process values display. After page load, transfer and update of only real data starts (here in interval 5 sec.), all other page elements stays without change. Live (real, instant) data are read from database on server, where are recorded by melting control system.
Original DHTML measuring points description and links to trend display pages are cut out in the example. Real time on page here is server real time, measured values are not taken from database, but are created by the help of random number generator. Number of points is only 4 here, compared to original 16 points.
Example looks very similar as basic screen of melting control system for visualisation. This intranet page can be displayed in browser for many hours and all the time displays actual data. Then just flight look on screen is enough for finding whether production process is under control. Web application interface do not offer so high comfort as control system does, but we do not need expensive licences, hardware keys, nor software installation. This application fits for remote, or occasional check of glass tank status.
CSS code
Few notes to CSS code at first. Cells for value display are using class Lb. In CSS section is only definition of basic appearance and dimensions of this class. Position (location) of particular cells are defined later as inline style, when cell <div> elements are instantieted in HTML code.
<style type="text/css">
.Lb {font: 13px Arial, SansSerif, Verdana; text-align: center;
position: absolute; width: 45px; height: 15px;
border: 1px solid #ccc; background: #fff; color: #006;}
</style>
<body>
...
<div style="position: relative; width: 580px; height: 326px;">
<img src="tank.png" style="width: 580px; height: 326px;" />
<div class="Lb" style="top:35px; left: 216px; width: 60px;
border: 0; background: transparent;">real time:</div>
<div id="d0" class="Lb" style="top: 35px; left: 280px; width: 132px;"></div>
<div id="d1" class="Lb" style="top: 131px; left: 193px;"></div>
<div id="d2" class="Lb" style="top: 171px; left: 257px;"></div>
<div id="d3" class="Lb" style="top: 262px; left: 190px;"></div>
<div id="d4" class="Lb" style="top: 262px; left: 290px;"></div>
</div>
...
</body>
Schematic picture of equipment and measuring point cells are placed into element <div>, which serves as container for these elements. Container has position relative so as inside of this container it was possible to use position absolute, and properties top, left for locating measuring point cells. Measuring point cells are situated approximately in sensor locations. Each cell has assigned its own id according to the sequence of values in Ajax data message.
Scripts
Ajax scripts debugging is more difficult than debugging DHTML scripts, or validation form scripts. Partial routines run on separated computers (client / server) and interact by sending messages over net. First part of script creates and sends request (run at browser), second part receives request, creates and sends back response (server script) and third part of script receives response and interpret data message (again run at browser). Such a break-up of scripts make problems in error locating.
If you are developing Ajax application on windows workstation IIS, consider the limit of 5 connected users. You can simultaneously debug Ajax code in two browsers only (one Ajax page counts as two users).
Browser script
Majority tutorials use similar code with detail explanation, therefore I drop here only inevitable description. Data transfer is provided by the help of XMLHttpRequest object, which transfers either XML, or plain text data. In this example plain text is transfered. Entire data transmission is handled by two functions: Next() performs creation and initialization of req object, sets up response process function, sends request and sets timer for next data transmission. Function processReq() tests response status, processes response data and writes out received data to the appropriate cells. Remains only to start action by performing last statement (line 30) after page loading.
1. <script type="text/javascript">
2. var req, URL = "getStatus.asp";
3. function processReq() {
4. if(req.readyState == 4) {
5. if(req.status == 200) {
6. var data = "";
7. data = req.responseText.split("|");
8. for(i=0; i<5; i++) {
9. document.getElementById("d" + (i)).innerHTML = data[i];
10. }
11. }
12. }
13. }
14.
15. function Next() {
16. delete req;
17. if (window.XMLHttpRequest) { // IE7, FF, Opera, ...
18. req = new XMLHttpRequest();
19. }
20. else if (window.ActiveXObject) { // <=IE6
21. req = new ActiveXObject("Microsoft.XMLHTTP");
22. }
23. if(req) {
24. req.onreadystatechange = processReq;
25. req.open("POST", URL, true);
26. req.send(null);
27. window.setTimeout("Next()", 5000);
28. }
29. }
30. window.onload = Next;
31. </script>
After complete data message is ready in browser, data are processed by lines 6-10. First, data row is split to single values (line 7), then in cycle (lines 8, 9, 10) values are inserted in the matching measuring cells. As a data separator character | (pipe) is used here in accordance with how data are prepared on server. To update the value in cell function document.getElementById("d" + (i)) is used to identify regular cell. Property innerHTML is not standardized, but all common browsers understand that. For the sake of simplicity there is no error testing conditions in script.
Server script
Server side script reads request parameters in the same way as reads form, or querystring data. In our example there is no need for parameters. Server task is to send message with prompt, real data. It is good practise to debug the server script separately, independently from browser code. You get the message by entering server script URL into browser address line. Then check the message by view source code of the page.
27.3.2007 21:14:30|1351|1446|361.2|721.6
Above is data message from this example. Notice that server script does not insert sections html, head, or body into data message. Only plain text is sent, individual items of data message are separated by pipe character.
Cache
One of the Ajax technology problem is browser cache. Browser saves data message received from server into its cache and at next request browser tries to read data from cache, not from server.
Cache is an advantage when more static content is requested, but when you need to transfer real dynamic data as it is in this example, cache memory needs to be eliminated. Therefore we have to set server script to immediate expiration. Such a setting is described in article IIS settings on this site. When you have not physical access to IIS server, ASP statement Response.AddHeader("Cache-Control", "no-cache") at the begining of server script prevents saving Ajax data into the browser cache too.
Other practise how to get always new data from server is URL with unique parameter at every request, but this method does not prevent saving data into cache. Time stamp can be used as a parameter. Following statement should be inserted after line 24.
URL = "getStatus.asp?t=" + ((new Date()).valueOf());
Code page
It is assumed to use UTF-8 encoding for Ajax data transmission. At only numeric data transmission there is no problem. Problem appears when data message contains non English text, characters with diacritic marks encoded in other code then UTF-8. Then question-marks are displayed instead of that special characters. Special characters in code UTF-8 occupy more bytes and if you decide to switch to UTF-8 code page, following problems apper: database design, text field length reservation, text ordering, searching, how to test maximum length of form input fields.
This problem troubled me some years ago when programming form with cascade select elements. The content of select element was bound to selection of previous select element and new content was transfered by help of Ajax. Sometimes normal Czech language was displayed, another time mixed with question-marks. In the end I give up Ajax solution. Too much encode and decode was required.
Ajax restriction
It is possible to use XMLHttpRequest object in browser only for data transmission in the same domain. Servers in other domain are not accessible by help of Ajax in browser.
updated 22.04.2007