Saturday, December 17, 2005

AJAX

I used to create web pages using a form which has a target in a hidden iframe. When the page is loaded. The data in the returned page is then parsed into the form using javascript. There is a problem with it as there is no way I can tell whether the data retrieval is available.

Recently I read about AJAX (Asynchronous JavaScript and XML). It seems to address the above problem. The following is a simple script that I used to get it working. It has three parts.

1. Javascript.
2. HTML form (omitted here)
3. PHP (server side script)

1. Javascript

Include the following two javascript functions in your calling page

//-------------------------------------------------------------------------------
function doget(query,query1){
Query = "mypage.php?department="+query+"&bft="+query1
try
req = new ActiveXObject("Msxml2.XMLHTTP.3.0");
catch (e)
try
req = new ActiveXObject("Microsoft.XMLHTTP");
catch (e)
try
req = new XMLHttpRequest()
catch(e)
req = false;


if (req){
req.onreadystatechange = processReqChange;
req.open("GET", query, true);
req.setRequestHeader('Content-Type','text/xml');
req.send();
}
else
alert("Cannot start XmlHttpRequest Object")
}

//-------------------------------------------------------------------------------

function processReqChange() {
// only if req shows "complete"
if (req.readyState == 4) {
// only if "OK"
if (req.status == 200) {
dbhtml="<table border=1 cellspacing=0><tr><th>Day</th><th>No of failure</th><th>No Calls</th><th>%</th></tr>"
response = req.responseXML.documentElement;
xdatalength=response.getElementsByTagName('day').length
for (x=0;x<=xdatalength-1;x++){
dateday = response.getElementsByTagName('day')[x].firstChild.data;
statcnt = response.getElementsByTagName('count')[x].firstChild.data;
statmiss = response.getElementsByTagName('miss')[x].firstChild.data;

dbhtml=dbhtml+"<tr><td>"+dateday+"</td><td>"+statmiss+"</td><td>"+statcn
t+"</td><td>"+Math.round((statmiss*1)/(statcnt*1)*100)+"</td></tr>"
}
// a DIV tag with a name "mydiv" must be defined for this to work properly
document.myform.mydiv.innerHTML=dbhtml+</table>
}
else
alert("There was a problem retrieving the XML data:\n" + req.statusText);
}

}
//-------------------------------------------------------------------------------

2. HTML

Just any html form that has a clickable item with has a "onclick" propert to initiate the "doget" function in the javascript. The "processReqChange" function is a callback function (automatically invoked by AJAX).

3. PHP

The php script is as follows (the database query section is omitted).
The first 4 lines must be at the top of the php page.

<?php
header('Content-Type: text/xml');
echo '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>';
echo "<response>";

/// your sql statement here using the passed parameters

while (odbc_fetch_row($rs))
{
$statcnt = odbc_result($rs,"statcnt");
$statmiss = odbc_result($rs,"statmiss");
$clsdate = odbc_result($rs,"cdate");
echo "<day>".$clsdate."</day>";
echo "<count>".$statcnt."</count>";
echo "<miss>".$statmiss."</miss>";
}
echo "</response>";
?>


Using ColdFusion instead of PHP is very simple... Just convert the php page to ColdFusion to return the same information. No need to change the calling page.

Note also that req.open in the above example is made using "GET"
method. If you need to send a lot of parameters (like submitting a form to be saved into database, then use "POST" method. The req.send function then must contain your parameters as a string. E.g.
req.send("department=xx&bft=yy")

Another thing to note is that if you are saving the submitted data then you don't have to use "req.responseXML.documentElement". Just use "alert(req.responseText)" to send a windows messge to user on the status of saving. Your PHP can forget about constructing the XML. Just "echo" some messge upon success or failure.

Note that the above is not synchronous but it is not multithreaded either. It only works on one particular way thus it cannot be used in multiple process to get data.

Tuesday, October 11, 2005

SVG calendar control

I have just uploaded the above into http://www.hiew.per.sg. File name is calendar.svg There are a number of input controls written in activex, java, javascript etc. This control is written in SVG. It does exactly as what the name provides. The control will replace a Input field with the name "svgdate" with the selected date. You can always modify it to work with different date format or even the field name of the parent document.


Alternatively you can insert definition "top.myfunction = mysvgfunction" into the svg script and create a function called mysvgfunction in svg to provide the date value then call myfunction from the parent script to get the date value. Obviously you must store the date variable as a svg global value.

Below is a simple web page to store the date string from the svg when user selects a date.

<html>
<head>
</head>
<body>
<form action="">
<input name="svgdate" type="text" value="" size="30">
<EMBED name="emap" pluginspage="http://www.adobe.com/svg/viewer/install/" src="calendar.svg" width="140" height="140" type=image/svg+xml>
</body>
</html>

Tuesday, September 13, 2005

Insert Multiple record in one sql statement

There are instances that one needs to insert multiple records into a database. This is normally for those people having a group of items to be insterted.

Normal SQL statement does a single record insert like below

INSERT INTO mytable (Field1,Field2...) VALUES (value1, value2...)

This is good for a single record insert. What happens is that a person may select a group of items like shopping cart. In the shopping cart you have the item code, quantity and perhaps price as one record. But if user selects more than one item then it caused a database update issue. Usually the server side will use a grouping of the item in a list and do a loop to insert the records one by one.

The above method worked fine if you only have a small list of item to update. In the commercial world, the requirement can end up with thousands of items each with several fields to update. To do update using the above method most probably caused timeout problem on the server side. It has to loop thousands of insert statement within one submission.

The under mentioned method is not my own idea but is copied from the internet while searching for solutions. I would like to give credit to the person/s but has lost the information. Anyway, thanks to the availablilty of this information, it solved my problems.

The multiple record insert SQL statement runs like below

INSERT INTO mytable (Field1, Field2,...)
SELECT valuea1,valuea2,....
UNION ALL
SELECT valueb1,valueb2,...
UNION ALL
SELECT valuec1,valuec2,...


I have tested the SQL statement with MS SQL SERVER and it worked. Not sure if other database server can also work the same way.

This method does has its limitation though. Obviously string variables will ultimately has a length limit. Moreover, to parse huge lengths of strings may cause resource problems. After all, the manupulations are done in the server itself.

Thursday, April 28, 2005

SVG BarCode 39

Posted a SVG based BarCode 39 sample program. The sample program can be found at http://www.hiew.per.sg .

This program is just a demo for BarCode generation. It does not fully conform to the BarCode 39 standard but the generated code should be able to be scanned correctly.

Code 39 gets its name from the way it is coded. It contains 5 bars and 4 spaces. each bar or space can be wide or narrow. Three of the bar of space must be wide. Thus the name 3 of 9.

The method of converting the text to ascii is quite simple. The translation codes are stored as text (in binary code) in an array. When user input a string, each character is then translated to its barcode binary by directly translating its ascii code as the array pointer.

The next step is to simply to translate that code as a series of rectangle or a move (if it is supposed to be a space code) using the SVG path command. The rectangle and space code is also stored in an array for easy retrieval by translating the binary code as value and retrieve the value depending on which array to take value from.

The code 39 start and stop character is simply stored as ascii 128 and is inserted before the parsing of the user input.

The inter character spacing is also coded together with the translation table for easy coding thus making the binary string as 10 digits. I used the simple form of the inter character space calculation using I=X (interspace equals smallest bar size). I also use the smallest ration of 1:2 between the narrow and wide code.

There is a limitation to the number of barcode that can be displayed. It depends on your Browser window as the width for the html embed statement is 100%. But by dynamically calculating the barcode width, you should be able to change it programmatically.

If you use viewbox in SVG, you should be able to shrink or expand the barcode overall size. But that means you must really conform to the code 39 specification of calculating the width and height of the overall size corresponding to the barcode width and height properly otherwise the scanner might not be able to decode it.

I have also created a barcode 39 font quite some years ago. This SVG BarCode39 program is based on the setting of the font I created. It took me a few days to create and test the font. Moreover, the font cannot be used on a web. I have to use WSH to convert it to web enabled form. It took me another few day to get the conversion working. It only took me half a morning to compelete the SVG barcode program. What a difference in coding time. However, barcode font can be used in windows. SVG barcode can only be used on web.

Monday, April 25, 2005

SVG Chart

Updated the SVG chart by standardizing the DOM interface for both manual and automation. The EMAScript is now moved to SVG itself. Calls are made to the EMAScript exposed function and values are passed into it.

This method is cleaner because all the necessary chart preparation are done right inside the SVG instead of at the javascript level at the Main page. The main page now just composes the information and passed the variables to the SVG to process. Therefore, the manual chart composition page (linechartform.html) and the automated php (not provided) are now using almost identical method calls.

Sunday, March 20, 2005

SVG Xiang Qi

Created a Chinese Chess Board game at http://www.hiew.per.sg.

Currently this game is just a simple game board with mouse clickable seeds. You can move the seed according to the Chinese Chess rule. Only rule not implemented is the Jiang to Shuai facing constrain.

Intend to add in the Player to Computer and Player to Remote Player interface. I am thinking of using existing Chess Engine for the Player to Computer interface. I am also thinking of using Java or XML-RPC to accomplish the peer-to-peer connection. Even thinking of using Existing IM interface to pass the moves.

A less real time mode will be using the PHP with session enabled and the session ID passed between two person so that they could use common variables. It means that the page will be an iframe in the main page that reloads at regular intervals of 1 sec. Since they use common session ID (by setting no cookies. A very bad practice of using the session id) Not bad if the number of users are small.

First user will login to the web page and in the process insert the session ID into the database. The second person simply login and look for the first person. Once selected, the first person's ID will be copied from the database and both can start to use common variables. Of course it does not stop a third person to access the session ID. The program will have to prevent any one other than the first two from playing.

Wednesday, March 09, 2005

SVG Charts

Added two charts at http://www.hiew.per.sg.

The Line Chart Form is for generating line charts and bar charts. Simple line and bar charts can be created by simply entering the data, separated by commas, into the input fields. You can experiment with the form and see immediate results in the chart below it.

The program is used in conjunction with Adobe SVG Viewer plugin. I is a very powerful Scalable Vector Graphic viewer that conforms to the WWW consortium svg standard.

The Line Chart Form also includes 5 different type of statistical line charts.

1. X-Bar Chart. (Up to 10 input lines. Can accomodate a lot of data.)
2. R Chart. (Up to 10 input lines. Can accomodate a lot of data.)
3. P Chart. (Only two lines are allowed. The first is the value. And the second the total. Percentage is calculated by the program.)
4. U Chart. (Only two lines are allowed. The first is the value. And the second the total.)
5. C Chart. (Up to 10 input lines. Can accomodate a lot of data.)

The calculations are all done externally to the SVG. It has not been tested thoroughly for calculation errors.

The Pie chart form is a simple flat pie chart program that also uses SVG to display. Up to a total of 16 pies can be created. I have not animate the pies to extend out when the mouse is over it.

Wednesday, February 16, 2005

Screen Reader Program

An ambitious attempt to write program handiling speech synthesis.

The program begins with the idea to create a speech synthesizer program that can read to user the text that was highlighted. It was then extended to enable it as a screen reader that could read mouse over icons names. This is very good for a blind person to read the screen.

Since the program is going to be free, I uses free program resources to do the programming.

First, I used BCX as a programming tool. BCX is a Basic to C compiler by Kevin Diggins. It is available at http://bcx-basic.sourceforge.net.

Next I use the Mbrola Speech API from http://tcts.fpms.ac.be/synthesis/mbrola.html. It is a diphone speech synthesizer engine. It is free for non commercial use.

I wrote the speech translation based on the Carnegie Mellon University speech dictionary at http://www.speech.cs.cmu.edu/cgi-bin/cmudict.

I also add a simple translation program based on adaptations from a number of programmers. The name of which I am unable to recall. My apologies.

The programming stops at the stage where I used window hooks to capture keystroke and pronounce the key typed. I am stuck with the accessible function where the window menus and icons properties can be retrieved.

Currently it worked as a standalone program with the main speech interface and my own translation interface as a dll. The reason being windows hook requires the call back function to be in a dll. I have used another windows hook (which does not need to be residing in a dll) since then but is too lazy to transform it back to the main exe.

Note. The souce code and the compiled program is not uploaded yet. i felt it useless to upload the program till the basic screen reader interface is completed. Thought of parking the program at sourceforge.

To do list.

1. integrate the screen reader function with the speech synthesizer. Currently, it can only read the text when user highlights it and press SHIFT-CTRL-Z.

2. Add windows menu and icon property reading.

3. speed up the reading translation interface. Currently it is quite slow with noticeable long pause between sentences (I break the reading of text by sentences so that long text can be pronounced without the full translation being completed.)

4. Adapt it to other OS. Currently it works on Win98 only. I tried XP and it hangged after a while.