Tornado Class Library

Special Topic - Using Ajax in Tornado

Tornado has streamlined the Ajax operations with minimum user input. 

The syntax of methods and properties within the scope of Ajax are as follow -

 

obj.dbAjax = true | False (Turns on Ajax - Default = false).

obj.dbAjaxName = Name of the Ajax container.

dbMyInputGetQueryString - Apply Ajax to dbMyInputFlds. Define the virtual path of the Validation program which get and process the querystring containing the inputs and return the appropriate messages.

 

What is Ajax and how does it work?

AJAX (Asynchronous JavaScript and XML) is based on JavaScript and HTTP requests. AJAX is made popular in 2005 by Google (with Google Suggest). AJAX is not a new programming language, but a new way to use existing standards. A very good tutorial can be found in http://www.w3schools.com/Ajax/default.asp.

Ajax basically involves the following items -

  1. A HttpRequest Javascript header file.
  2. A Form submit event.
  3. A defined location (container) for the result to be placed without repainting the page.
  4. An external program (.aspx) to process the information submitted by the Form and returns the appropriate messages. These messages will be placed in the container.

     

How does Tornado implement Ajax?

Tornado applied and streamlined Ajax in the following ways -

  1. Regular Grid display w/o reapint. By just specifying obj.dbAjax = True.
  2. Dynamic list display. By just specifying obj.dbAjax = True. This implementation reclaims the classic ASP 'Remote Scripting' feature in DotNet.
  3. Validate the input fields of the dbMyInputFlds feature and returns the validation messages with screen refresh.

 

 

Dynamic List Example

When Ajax is used in Dynamic List, it has the same effect as the classic ASP 'remote scripting' in which all the event and response will not repaint the page. Look at the code of the 3 elements of the Dynamic List - Main code, HTML template and the trigger output.

HTML template (ajax-dlist-in.html) - This is the code that layout the HTML elements.

<center><table>
<tr><td>Year</td><td>Manufacturer</td><td>Vehicle</td></tr>
<tr><td>[[Level0]]</td><td>[[Level1]]</td><td>[[Level2]]</td></tr>
</table></center><p><div id='DLDEMO'></div>

Not that we place the Ajax container at the end of the table as <div id='DLDEMO'></div>. The triggered output will go into this container. The container code is hard coded (preferred way) in the template file. The alternative is to tell Tornado to place that in the Anchor using dbTextHolder = "BEB=<div id='DLDEMO'></div>".

 

Output Code (ajax-dlist-out.aspx) - This code reads the FORM variable passed from the  from the main code and returns the Triggered output via response.write. The response.write text will go into the container of the template with Ajax in action.

<script language="vb" runat="server">
Sub Page_Load(Source as Object, E as EventArgs)
Dim Sel As String = Request.Querystring("ASPdbDlistSubmit")
Dim GD As New Tornado.GetData() 
Dim DY0 As New Tornado.z()
Dim Fexp() As String
With DY0
.dbMode = "grid"
.dbSkin = 5
.dbUnit = 56
.dbDSN = "CAR2000"
.dbSQL = "SELECT * FROM Carspecs WHERE car = '" & Sel & "'"
.dbInvisible = True
.dbExportFlds = "*"
.dbMemoTextSize = -1
.AspdbNET()
Fexp = GD.Get_Fexport()
End With
'... the following output will go to the Ajax container DLDEMO
Response.Write("<table Cellspacing='5' cellpadding='3'><tr><td align='left'>" & "Price: " & Format(Fexp(4), "Currency") & "<BR>" & 
"Transmission: " & Fexp(3) & "<BR>" & "Engine: " & Fexp(5) & "<BR>" & "MPG: " & Fexp(6) & "</td><tr><td>" & 
"<IMG SRC='/Tornado/DB/images-car/" & Fexp(7) & "'></td></tr><tr><td align='left'>" & Fexp(8) & "</td></tr></table>")

End Sub
</Script>

 

Main Code (ajax-dlist.aspx) - This code ties the template and output.

<script language="vb" runat="server">
Sub Page_Load(Source as Object, E as EventArgs)
Dim Sel As String = Request.Form("ASPdbDlistSubmit")
Dim dy3 As New Tornado.z()
With dy3
.dbUnit = 505
.dbSkin = 5
.dbDSN = "CAR2000"
Dim s As String = "InputHtml=file=/tornado/work/ajax-dlist-in.html| OutputAspx=file=/tornado/work/ajax-dlist-out.aspx"
s &= ";level=0|label=[Select a year]|table=Carspecs|field='Yr'|DroptextIndex=0;"
s &= "level=1|label=[Select a Manufacturer]|table=Carspecs|field='Manufacturer'|DroptextIndex=0;"
s &= "level=2|label=[Select Car]|table=Carspecs|field='car'"
.dbDynalist = s
'....dbTextHolder = "title=ASPdb Dynalist Demo - Table and Fields only|subtitle=5 lines of code for a 3 levels Dynamic List| BEB=<div id='DLDEMO'></div>"
.dbTextHolder = "title=ASPdb Dynalist Demo - Table and Fields only|subtitle=5 lines of code for a 3 levels Dynamic List"
.dbAjaxName = "DLDEMO"
.dbAjax = True
.ASPdbDynaList()
End With
End Sub
</Script>

Note that dbAjaxname defines the Ajax container name and dbAjax is set to true.

 

Ajax MyInputFlds and Image Verification Example

MyInputFlds allows user to build a feature rich input page with only dress up codes. Ajax as well as an Image Verification is added to further enhance the features. The following items when added will implement an Ajax validation -

  1. obj.dbAjax = True
  2. obj.dbAjaxName = "MYERRAJAX" - defines the Ajax container
  3. obj.dbMyInputGetQueryString = "/MySIte8/Reg/RegValidate.aspx" - defines the virtual location of the validating program.

 

Main Code (Reg.aspx) - Define the Input fields. Image verification is also added

<script language="vb" runat="server">
Sub Page_Load(Source as Object, E as EventArgs)
   Dim ActiveDir = "/"
   Dim MyServer As String = Request.ServerVariables("SERVER_NAME")
   If InStr(1, MyServer, "codeangel", 1) > 0 Then
      ActiveDir = "/"
   End If
   Dim ImgVirPath = ""
   Dim Mi As New Tornado.z
   Mi.dbMyInputGetQueryString = "/MySIte8/Reg/RegValidate.aspx" '.. if this is error the Ajax will display error
   Dim RandomClass As New Random()
   Dim ImageText As String = RandomClass.Next(10000, 99999).ToString()
   Session("ImageText") = ImageText
'... setup verify image
   Mi.ImageVerify(ImageText, ActiveDir & "/tornado/Scratch/" & ImageText & ".jpg")

   ImgVirPath = "/tornado/Scratch/" + Session("ImageText").ToString() + ".jpg"
   Mi.dbQP = "U=88|S=ASPdb|th=tit=CodeAngel Registration"
   Dim inp As String = "(;~)"
   inp &= "Fi=uTitle;Title: | Ty=SelectBox| Val={{Mr.,Mrs.,Ms.,Dr.}}| BR=<br />~"
   inp &= "Fi=uName;Name: | type= TEXT| Tag=SIZE='35'| Notes=First Init. Last| BR=<br />~"
   inp &= "Fi=uAlias;Alias: | type=TEXT| Tag=SIZE='25'| Notes=Unique ID/handle| BR=<br />~"
   inp &= "Fi=uPass;Password: | type=Password| Tag=SIZE='25' autocomplete='off'| BR=<br />~"
   inp &= "Fi=uPass1;Re-Enter Password: | type=Password| Tag=SIZE=25 autocomplete='off'| BR=<br />~"
   inp &= "Fi=uAddress; Mailing Address: | type=TEXTAREA| Tag=Cols='51' Rows='5'| def=Optional| BR=<br />~"
   inp &= "Fi=uPhone;Phone: | type=TEXT| Tag=Size='25'| Notes=Country code & ext.| def=Optional| BR=<br />~"
   inp &= "Fi=uemail;Email: | type=TEXT| Tag=Size='25'| Notes=Confirmation sent| BR=<br />~"
   inp &= "Fi=uemail1;Re-Enter Email: | type=TEXT| Tag=Size='25'| Notes=to this address| BR=<br />~"
   inp &= "Fi=none|type=USER| Def=<IMG SRC='" + ImgVirPath + "' />| BR=<br />~"
   inp &= "Fi=uimageverification;Image Verification: | type=TEXT| Notes=Type the above Text| BR=<br />"

   Mi.dbMyInputFlds = inp
   Mi.dbAjax = True
   Mi.dbAjaxName = "MYERRAJAX"  '... validation results will go here
   Response.Write(Mi.ASPdbMyInputForm())
End Sub
</Script>

 

Validation Code (RegValidate.aspx) - This code parses the passing querystring, validates that and returns the messages to the main code container.

<script language="vb" runat="server">
Sub Page_Load(Source as Object, E as EventArgs)
'... Response.write("Q=" & Request.QueryString().tostring())
   Dim tit As String = Request.QueryString("uTitle")
   Dim nam As String = Request.QueryString("uname")
   Dim al As String = Request.QueryString("ualias")
   Dim addr As String = Request.QueryString("uaddress")
   Dim phone As String = Request.QueryString("uphone")
   Dim imgver As String = Request.QueryString("uimageverification")
   Dim em As String = Request.QueryString("uemail")
   Dim em1 As String = Request.QueryString("uemail1")
   Dim pass As String = Request.QueryString("upass")
   Dim pass1 As String = Request.QueryString("upass1")
   Dim err As String = ""
   If nam = "" Then err += "<li>Name cannot be blank.</li>"
   If al = "" Then err += "<li>Alias/handle cannot be blank.</li>"
   If em <> em1 Or em + em1 = "" Then err += "<li>Invalid Email addresses - Re-enter email address.</li>"
   If pass <> pass1 Or pass + pass1 = "" Then err += "<li>Invalid Passwords - Re-enter passwords.</li>"
   If addr = "" Then err += "<li>Mailing Address cannot be blank.</li>"
   If imgver <> Session("ImageText") Then err += "<li>Invalid Image Text verification.</li>"
   If err <> "" Then
         Response.Write("<b>Form Submit Error</b><table class='TS' width='80%'><tr><td align='left'><ol>" & err & "</ol></td></tr></table>")
      Else
'... the following code allows you to develop in localhost and also in myurl.
         Dim ActiveDir = "/MyURL"
         Dim MyServer As String = Request.ServerVariables("SERVER_NAME")
         If InStr(1, MyServer, "myurl", 1) > 0 Then
            ActiveDir = "/"
         End If
         Dim MySMTP As String = "smtp.myurl.com"
         If InStr(1, MyServer, "muyrl", 1) > 0 Then
            ActiveDir = "/"
            MySMTP = "localhost"
         End If
         Dim db As String = Server.MapPath(ActiveDir + "/tornado/DB/CA.MDB")   '...CA is the registration DB

         Dim Mi As New Tornado.z
         Mi.dbQP = "u=77|Q=Users|BM=CA;0|dt=access|D=" & db
         Mi.dbSuppressMsg = True
         Mi.dbDebug = "EditAction"
         Dim val As String = String.Format("('{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}')", pass, tit, nam, al, em, addr, phone, Date.Now().ToString("MMM dd yyyy"))
         Mi.dbSilentCmdText = "com=INSERT INTO Users (usPassword, usTitle, usName, usAlias, usEmail, usAddress, usPhone, usRegdate) VALUES " & val
         If Mi.ASPdbExecuteCmd() > 0 Then  '... if registration is good then write to DB and then send an alert email
            err = "Registration Success."
            Response.Write("<b>Form Submit Status</b><table class='TS' width='80%'><tr><td align='left'>" & err & "</td></tr></table>")
            Mi.dbMail = String.Format("test=false| smtp={8}| From={4}|to=sales@codeangel.net|subject=CodeAngel Registration| Body=Registrant info -<br>Password={0}<BR>Name={1} {2}<br>Alias={3}<br>email={4}<br>Address={5}<br>Phone={6}<br>Now={7}", pass, tit, nam, al, em, addr, phone, Date.Now(), MySMTP)
            Mi.ASPdbSendMail()
         Else
            Dim adderr As String = Session("SILENTCMDERROR")
            If InStr(adderr, "duplicate values") > 0 Then '...detect special error conditions - dup values
               err = "Duplicated Alias - Pick another unique value."
               Response.Write("<b>Form Submit Error</b><table class='TS' width='80%'><tr><td align='left'><ol>" & err & "</ol></td></tr></table>")
            Else
               err = "Error in adding record to database - contact support@myurl.com."
               Response.Write("<b>Form Submit Error</b><table class='TS' width='80%'><tr><td align='left'>" & err & "</td></tr></table>")
            End If
         End If
   End If
End Sub
</script>

 

 


Send comments on this topic.
Copyright 1998-2009 ASP-db