JavaScript Editor JavaScript Validator     JavaScript Editor 



Team LiB
Previous Section Next Section

Chapter 16

In this chapter we looked at running our scripts server-side, how running scripts sever-side differed from running them client-side, and using ASP objects.

Question 1

Q: 

 

Alter the logon example from this chapter, so that if a user enters an invalid value more than three times the user is not taken back to the logon page, but to another page that says the user is not a valid user.

A: 
<%@ language = JavaScript %>
<html>
<head>
<script language=JavaScript>
    
function form1_onsubmit()
{
   var form = document.form1;
   var returnValue = false;
    
   if (form.txtUsername.value == "")
   {
      alert("Please enter your username");
      form.txtUsername.focus();
   }
    
   else if (form.txtPassword.value == "")
   {
      alert("Please enter your password");
      form.txtPassword.focus();
   }
   else
   {
      returnValue = true;
   }
    
   return returnValue;
}
    
</script>
</head>
<body>
<%
if (Request.Form.Count != 0)
{
   if (Request.Form("txtUsername") == "SecureUser" &&
      Request.Form("txtPassword") == "letmethrough")
   {
      Response.Cookies("IsValid") = "Yes";
      Response.Redirect("SecureHome.asp");
   }
   else
   {
      Session("LogonTrys") = parseInt(Session("LogonTrys")) + 1;
      Response.Redirect("logon.asp")
   }
}
    
var invalidTrys = Session("LogonTrys");
if (isNaN(invalidTrys))
{
   invalidTrys = 1;
   Session("LogonTrys") = invalidTrys;
}
else
{
   invalidTrys = parseInt(invalidTrys);
}
    
if ( invalidTrys != 1 )
{
   Response.Write("<P><font color=red size=+2>"+ "Sorry the username/password" +
      " you entered were invalid</font></P>")
   if ( invalidTrys <= 3)
   {
      Response.Write("<P><font color=black size=+2>"+
                     "Please re-enter your details" +
                     "</font></P>")
   }
}
    
if ( invalidTrys <= 3)
{
%>
<P> To access this website please enter your username and
   password in the boxes below</P>
    
<form action="LogOn.asp" method=post id=form1 name=form1
      onsubmit="return form1_onsubmit()">
    
<P>Username : <input id=txtUsername name=txtUsername></P>
<P>Password : <input id=txtPassword name=txtPassword type=password></P>
    
<P>
<input id=reset1 name=reset1 type=reset value=Reset>&nbsp;
<input id=submit1 name=submit1 type=submit value="Log On">
</P>
</form>
<%
}
%>
</body>
</html>

Save this as LogOn.asp.

What I've done with the example in the chapter is modify it so it limits the user to three attempts, and it is now just one page, LogOn.asp, rather than two pages, LogOn.htm and CheckLogon.asp. LogOn.asp contains both the form, which posts to itself, and the check for logon validity.

The first change is that the page's file extension is .asp rather than .htm; this is to allow us to insert script that runs on the server-side. We then add

<%@ language = JavaScript %>

This is to instruct the server to run the server-side scripts on that page in the JavaScript language. Remember that by default it's VBScript.

The client-side scripting remains unchanged from the earlier example—the next change is the addition of a big server-side script block after the <body> tag, so let's look at it step by step.

The first part checks the logon details submitted. We need to check if this page is being loaded due to a form submission (remember this page has a form, which submits to this same page). The Request.Form.Count lists the number of form elements whose values have been submitted. If it's zero, it means either a form with no elements was submitted or, as in this case, that the page has not been loaded as a result of a form submission. If it's not zero, this page has been loaded by a form submission, and therefore we need to check the user logon details. If the user is a valid user, we redirect him to the SecureHome.asp page. If not, we increase the variable, LogonTrys, which stores the number of attempts that the user has made to log in and let the page continue loading.

<%
    
if (Request.Form.Count != 0)
{
   if (Request.Form("txtUsername") == "SecureUser" &&
       Request.Form("txtPassword") == "letmethrough")
   {
      Response.Cookies("IsValid") = "Yes";
      Response.Redirect("SecureHome.asp");
   }
   else
   {
      Session("LogonTrys") = parseInt(Session("LogonTrys")) + 1;
   }
}

Our next bit of server-side code deals with the number of logon attempts the user has made in this session. If this is the first time in this session that he has loaded the page, then Session("LogonTrys") won't contain any value, so we assign it the value of 1. Otherwise we retrieve its value and store it as an integer in variable invalidTrys.

var invalidTrys = Session("LogonTrys");
if (isNaN(invalidTrys))
{
   invalidTrys = 1;
   Session("LogonTrys") = invalidTrys;
}
else
{
   invalidTrys = parseInt(invalidTrys);
}

Then we come to the server-side code that displays a message telling the user that the logon/username was invalid. If this is the first time the user has been to this page, clearly the user has not yet had a chance to enter logon details, valid or otherwise. If it's not the user's first time here, he can only have arrived back because he submitted an invalid username or password. So if invalidTrys is not 1, it's not the user's first time here this session, and so we display the invalid logon message. If the number of retries is less than 3, we also display a message telling the user to re-enter the details and try again.

if ( invalidTrys != 1 )
{
   Response.Write("<P><font color=red size=+2>"+
                  "Sorry the username/password" +
                  " you entered were invalid</font></P>")
   if ( invalidTrys <= 3)
   {
      Response.Write("<P><font color=black size=+2>"+
                     "Please re-enter your details" +
                     "</font></P>")
   }
}

The final bit of server-side code is wrapped around some HTML, in particular the form that allows the user to enter a username and password. If the user has made three attempts or less, the if statement will let the form HTML be written to the page and displayed to the user. If the user has already entered it wrong three times, no form is displayed this session for a fourth attempt, and only by closing his browser and navigating to the page's URL again will the user be able to try again.

if ( invalidTrys <= 3)
{
%>
<P> To access this website please enter your username and
password in the boxes below</P>
    
<form action="LogOn.asp" method=post id=form1 name=form1
      onsubmit="return form1_onsubmit()">
    
<P>Username : <input id=txtUsername name=txtUsername></P>
<P>Password : <input id=txtPassword name=txtPassword type=password></P>
    
<P>
<input id=reset1 name=reset1 type=reset value=Reset>&nbsp;
<input id=submit1 name=submit1 type=submit value="Log On">
</P>
    
</form>
<%
}

Question 2

Q: 

 

In Question 2 of Chapter 6 and continuing with Question 1 of Chapter 7, we created a form that allowed users to select their dream computer systems and to see the price change as they selected different components. Our task for this question is to enable the users to purchase the system they have selected. This involves the following conditions:

  • When the user clicks to buy the system, we need to obtain all the information necessary for an e-commerce purchase, for example name, address, and credit card details.

  • With all the information obtained, show a final summary page that displays the system selected, its price, and the user's details. There should be a confirm order button and a cancel order button on the page.

  • If the user clicks the confirm order button, the system is purchased: Simply take the user to a page saying, "Thanks for your order." If the user cancels the order, then wipe out the user details and return the user to the home page.

A: I'm re-using the exercise answers from Chapter 7. First we need a top frameset page, identical to the one used in Chapter 7, Question 1. This time I've called it ch16Q2_TopFrame.htm.
<html>
<head>
</head>
<frameset cols="55%,*">
   <frame src="ch16Q2_PickSystem.htm" name="pickSystem">
   <frame src="blank.htm" name="systemSummary">
</frameset>
</html>

We'll also need a blank HTML file, blank.htm, like so:

<html>
<body>
</body>
</html>

Then we have the page that allows the user to pick the system, ch16Q2_PickSystem.htm. This is virtually identical to the version of PickSystem.htm in Chapter 7, apart from differences in two places. The first is at the top of the updateOrderDetails() function.

function updateOrderDetails()
{
   var total = 0;
   var orderDetails = "<H3>Your selected system</H3>";
   var orderForm = "";
   var formElement;

The second is toward the end of the function.

   else
   {
      orderDetails = orderDetails + "Full Tower Case : $" +
                     CompItems[formElement[2].value]
      total = total + parseFloat(CompItems[formElement[2].value]);
   }
    
   orderForm = orderForm + "<form action='ch16Q2_BuySystem.asp' method=post "

               + "name=form1 TARGET=_top><input type='submit' "
               + "value='Buy System'>"
               + "<input type='hidden' name='txtCost' "
               + " value='" + total + "'>"
               + "<input type='hidden' name='txtDescription' "
               + "value='" + orderDetails + "'></form>"
    
   orderDetails = orderDetails + "<P>Total Order Cost is $" + total + "</P>";
    
   window.parent.systemSummary.document.open();
   window.parent.systemSummary.document.write(orderDetails + orderForm);
   window.parent.systemSummary.document.close();
}

Save this as ch16Q2_PickSystem.htm.

Next we have our first new page, the one that is loaded when the Buy System button is clicked.

<%@ language=JavaScript %>
<html>
<head>
<title>Buy System</title>
    
<script language=JavaScript>
    
function checkForm()
{
   var regExp = /[^\d ]/
   var formValid = true;
   var theForm = document.form1;
   var elementIndex;
   var element;
   var nowDate = new Date();
   var expMonth = parseInt(theForm.selMonth.value)
   var expYear = parseInt(theForm.selYear.value)
    
   for (elementIndex = 0; elementIndex < theForm.length; elementIndex++)
   {
      element = theForm[elementIndex];
      if (element.type == "text")
      {
         if (element.value == "")
         {
            formValid = false;
            element.focus();
            alert("Please complete all of the boxes");
            break;
         }
      }
   }
    
   if (formValid == true && expYear <= parseInt(nowDate.getFullYear()) &&
parseInt(nowDate.getMonth()) > expMonth)
   {
      formValid = false;
      theForm.selMonth.focus();
      alert("The credit card expiration date you selected has expired")
   }
   else if (regExp.test(theForm.txtCCNumber.value) == true)
   {
      formValid = false;
      alert("Please enter a valid credit card number");
      theForm.txtCCNumber.focus();
      theForm.txtCCNumber.select();
   }
    
   return formValid;
}
    
</script>
    
</head>
<body>
<H2>Purchase System</H2>
<P>Please enter you name, address and credit card details below</P>
<form action="ch16Q2_FinalStage.asp" method=post name=form1 onsubmit="return
checkForm()">
<P>
Your Full Name:
<br>
<input type="text" name=txtName>
</P>
<P>
House Name/Number
<br>
<input type="text" name=txtHouse>
</P>
<P>
Street:
<br>
<input type="text" name=txtStreet>
</P>
<P>
City:
<br>
<input type="text" name=txtCity>
</P>
<P>
<P>
Credit Card Number:
<br>
<input type="text" name=txtCCNumber>
<P>
Expiration Date
<br>
<select name=selMonth>
<option value="01">01</option>
<option value ="02">02</option>
<option value ="03">03</option>
<option value ="04">04</option>
<option value ="05">05</option>
<option value ="06">06</option>
<option value ="07">07</option>
<option value ="08">08</option>
<option value ="09">09</option>
<option value ="10">10</option>
<option value ="11">11</option>
<option value ="12">12</option>
</select>
<select name=selYear>
<%
    
var yearCount;
var nowYear = new Date();
nowYear = parseInt(nowYear.getFullYear());
    
for (yearCount = nowYear; yearCount < nowYear + 5; yearCount++)
{
   Response.Write("<option value='" + yearCount + "'>")
   Response.Write(yearCount + "</option>");
}
    
%>
    
</select>
    
<input type="hidden" name="txtCost" value="<%=Request.Form("txtCost")%>">
    
<input type="hidden" name="txtDescription"
       value="<%=Request.Form("txtDescription")%>">
<P>
<input type="submit" value="Submit" name=submit1>
</P>
</form>
</body>
</html>

Save this as ch16Q2_BuySystem.asp.

Next we have the ch16Q2_FinalStage.asp page, which displays a summary of the user's order and order details and gives the user the chance to purchase or cancel the order.

<%@ language = JavaScript %>
<html>
<head>
<title>Final Summary</title>
</head>
<body>
    
<H3>Order Summary</H3>
    
<%
    
var description = Request.Form("txtDescription").item;
var cost = Request.Form("txtCost").Item
var name = Request.Form("txtName").Item
var houseNo = Request.Form("txtHouse").Item
var street = Request.Form("txtStreet").Item
var city = Request.Form("txtCity").Item
var ccNumber = Request.Form("txtCCNumber").Item
    
var expiryDate = Request.Form("selMonth") + "/" +Request.Form("selYear")
    
Response.Write ("<P>" + description + "</P>")
Response.Write ("<P>Will be delivered to </P>")
Response.Write ("<P>Name : " + name + "</P>")
Response.Write ("<P>At address</P>")
Response.Write ("<P>" + houseNo + " " + street + "<br>")
Response.Write (city)
Response.Write ("<P>Your credit card " + ccNumber)
Response.Write (" expiration date " + expiryDate)
Response.Write (" will be debited by $" + cost)
    
%>
    
<form action="ch15Q2_PurchaseOrder.asp" method=post name=form1>
<input type="hidden" name="txtName" value ="<%=name%>">
<input type="hidden" name="txtDescription" value ="<%=description%>">
<input type="hidden" name="txtCost" value ="<%=cost%>">
<input type="hidden" name="txtHouseNo" value ="<%=houseNo%>">
<input type="hidden" name="txtStreet" value ="<%=street%>">
<input type="hidden" name="txtCity" value ="<%=city%>">
<input type="hidden" name="txtCCNumber" value ="<%=ccNumber%>">
<input type="hidden" name="txtExpiryDate" value ="<%=expiryDate%>">
<input type="submit" value ="Purchase System" name=submit1>
<P>
<input type="button" value="Cancel Purchase" name=butCancel
             onclick="window.location.replace('Ch16Q2_TopFrame.htm')" >
</P>
</form>
    
</body>
</html>

Finally, we have the ch16Q2_PurchaseOrder.asp page that does the actual purchase of the system, or at least it would if this were not an example!

<%@ language=JavaScript %>
<html>
<head>
<title>Order Completed</title>
</head>
<body>
    
<H3>Thank you for your order <%=Request.Form("txtName")%>
<br> it'll be with you shortly
</H3>
    
</body>
</html>

Save this page as ch16Q2_PurchaseOrder.asp.

Let's take a brief look at how it all works; I won't cover the bits we did in Chapters 6 and 7, just the additions.

First in ch16Q2_PickSystem.htm, we added the following code:

   orderForm = orderForm + "<form action='Ch16Q2_BuySystem.asp' method=post "

               + "name=form1 TARGET=_top><input type='submit' "
               + "value='Buy System'>"
               + "<input type='hidden' name='txtCost' "
               + " value='" + total + "'>"
               + "<input type='hidden' name='txtDescription' "
               + "value='" + orderDetails + "'></form>"

When the user clicks the update button to view the system she has chosen, not only is the HTML necessary to display the system written to the page, but now we also write an HTML form that contains a button called Buy System and two hidden input boxes, which we discussed in Chapter 6, that contain details of the system the user wants and the cost. When the Buy System button is clicked, the form will submit to the first of our new pages, ch16Q2_BuySystem.asp.

Let's start at the top of ch16Q2_BuySystem.asp.

First, since we want to use JavaScript as our server-side scripting language we have

<%@ language=JavaScript %>

Next we have a block of client-side script which contains the function checkForm().

This function does some basic checks to see that all the input boxes have been filled in, a valid date has been selected for the credit card expiration date, and the credit card number only contains permitted characters (that is, numbers and spaces).

If any of these tests fails, we alert the user and stop the form submit from continuing by returning false from the function to the event handler it was called from.

Next we come to the form itself, where users enter their details, such as name, address, and credit card number. Most of the form should be fairly self-explanatory except this: the credit card expiration year select box.

<select name=selYear>
<%
    
var yearCount;
var nowYear = new Date();
nowYear = parseInt(nowYear.getFullYear());
    
for (yearCount = nowYear; yearCount < nowYear + 5; yearCount++)
{
   Response.Write("<option value='" + yearCount + "'>")
   Response.Write(yearCount + "</option>");
}
    
%>
</select>

Rather than write in the years ourselves, we've used some server-side script to create the <option> tags with a series of five years starting from the current year. The advantage of that is we don't need to change our page for it to be up-to-date. So even if you're reading this appendix in 2030, the years will still be valid—that is, 2030, 2031, 2032, 2033, and 2034. I wrote the month's select box in myself, and although it would save typing to have JavaScript create them, it would add an extra and unnecessary load on the server for it to dynamically create them for each page load. If you're wondering why select rather than text input boxes have been chosen to get the expiration date, it's because this helps prevent validation errors. If we asked the user for the expiration date, there is a danger she will enter it in an unexpected or invalid format, and we'd have to write lots of code to check for this situation. With select boxes, the user has no choice but to get the format right.

Finally we have two hidden input boxes, their purpose being to hold the information (the system description and cost) posted from the last page.

<input type="hidden" name="txtCost" value="<%=Request.Form("txtCost")%>">
<input type="hidden" name="txtDescription"
   value="<%=Request.Form("txtDescription")%>">

Hidden input boxes are a very useful way of transferring information from page to page when using form submits, because you have no need for server variables or cookies.

Next we come to ch16Q2_FinalStage.asp, where we display a summary of what the user has entered so she can check the order details before finally committing to it.

First we have the server-side code that retrieves the posted form details and uses it to write a summary to the page before it's sent to the client browser.

<%
    
var description = Request.Form("txtDescription").item;
var cost = Request.Form("txtCost").Item
var name = Request.Form("txtName").Item
var houseNo = Request.Form("txtHouse").Item
var street = Request.Form("txtStreet").Item
var city = Request.Form("txtCity").Item
var ccNumber = Request.Form("txtCCNumber").Item
    
var expiryDate = Request.Form("selMonth") + "/" +Request.Form("selYear")
    
Response.Write ("<P>" + description + "</P>")
Response.Write ("<P>Will be delivered to </P>")
Response.Write ("<P>Name : " + name + "</P>")
Response.Write ("<P>At address</P>")
Response.Write ("<P>" + houseNo + " " + street + "<br>")
Response.Write (city)
Response.Write ("<P>Your credit card " + ccNumber)
Response.Write (" expiry date " + expiryDate)
Response.Write (" will be debited by $" + cost)
    
%>

Finally we have a form, most of which is hidden input boxes that contain all the order details received so far. When the user clicks the Purchase button, all the information will be submitted in one go. It's much easier to deal with all the information for a transaction at once rather than try to do it in little stages. Otherwise we'd need to deal with the possible situation where the user changes her mind halfway through or where her computer, browser, or connection terminates unexpectedly.

<form action="Ch16Q2_PurchaseOrder.asp" method=post name=form1>
<input type="hidden" name="txtName" value ="<%=name%>">
<input type="hidden" name="txtDescription" value ="<%=description%>">
<input type="hidden" name="txtCost" value ="<%=cost%>">
<input type="hidden" name="txtHouseNo" value ="<%=houseNo%>">
<input type="hidden" name="txtStreet" value ="<%=street%>">
<input type="hidden" name="txtCity" value ="<%=city%>">
<input type="hidden" name="txtCCNumber" value ="<%=ccNumber%>">
<input type="hidden" name="txtExpiryDate" value ="<%=expiryDate%>">
<input type="submit" value ="Purchase System" name=submit1>
<P>
<input type="button" value="Cancel Purchase" name=butCancel
             onclick="window.location.replace('Ch16Q2_TopFrame.htm')" >
</P>
</form>

The very last page is ch16Q2_PurchaseOrder.asp, in which we simply say thank you for buying the system. In reality this is where all the order processing would be done, such as placing the order details in a database, processing the credit card, and ensuring that the orders department is told to send the system.


Team LiB
Previous Section Next Section


JavaScript Editor JavaScript Validator     JavaScript Editor


©