Hack 6. Receive Data as a Number


Do numerical calculations that depend on the request object's return value as a number.

This hack receives a stock quote as a number, then dynamically displays the total value of a stock holding based on the number of shares a user enters. If the server does not send a valid number, the application displays an error message to the user.

The great advantage of Ajax technology is in receiving discrete values rather than entire web pages from a server. Sometimes, that discrete information has to be used as a number, rather than as a string (as discussed in the last hack) or some other object. JavaScript is usually pretty smart about converting values to number types without your intervention, but still, you don't want your application to multiply an innocent investor's share quantity by undefined or some other weird data the server returns!

This hack checks that the user has entered a proper number for a "number of shares" value. The code also checks the server return value to make sure it is numerically valid. It then dynamically displays the stock price and total value of the shares in the user's browser.

Figure 1-6 shows what the browser form looks like.

Figure 1-6. Discover a total share value


The following code shows the HTML for the web page:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"         "http://www.w3.org/TR/1999/REC-html401-19991224/strict.dtd"> <html> <head>     <script type="text/javascript" src="/books/4/254/1/html/2//parkerriver/js/hack4.js">     </script>     <meta http-equiv="content-type" content="text/html; charset=utf-8" />     <title>Tally your stocks</title> </head> <body> <h3>Your total Stock Holdings</h3> <form action="javascript:void%200" onsubmit=         "getStockPrice(this.stSymbol.value,this.numShares.value);return false"> <p>Enter stock symbol: <input type="text" name="stSymbol" size="4">             <span ></span></p> <p>Enter share amount: <input type="text" name="numShares" size="10"></p> <p><button type="submit">Get Total Value</button></p> <div ></div> </form> </body> </html>

When the user clicks the Get Total Value button, this action triggers the form element's onsubmit event. The event handler for this event is the getStockPrice( ) function. This function takes the stock symbol and the number of shares as its two parameters. The return false part of the event-handling code cancels the browser's typical submission of the form values to the URL specified by the form tag's action attribute.

Number Crunching

Now let's look at the JavaScript code, which the HTML file imports as part of the hack4.js file:

var request; var symbol;   //will hold the stock symbol var numberOfShares; function getStockPrice(sym,shs){     if(sym && shs){         symbol=sym;         numberOfShares=shs;         var url="http://localhost:8080/parkerriver/s/stocks?symbol="+sym;         httpRequest("GET",url,true);     } } //event handler for XMLHttpRequest function handleResponse(  ){     if(request.readyState == 4){         alert(request.status);         if(request.status == 200){             /* Check if the return value is actually a number.              If so, multiple by the number of shares and display the result */             var stockPrice = request.responseText;             try{                 if(isNaN(stockPrice)) { throw new Error(                         "The returned price is an invalid number.");}                 if(isNaN(numberOfShares)) { throw new Error(                         "The share amount is an invalid number.");}                 var info = "Total stock value: "+  calcTotal(stockPrice);                 displayMsg(document.                 getElementById("msgDisplay"),info,"black");                 document.getElementById("stPrice").style.fontSize="0.9em";                 document.getElementById("stPrice").innerHTML ="price:                  "+stockPrice;             } catch (err) {                 displayMsg(document.getElementById("msgDisplay"),                         "An error occurred: "+                         err.message,"red");             }         } else {             alert(                     "A problem occurred with communicating between the "+                     "XMLHttpRequest object and the server program.");         }     }//end outer if } /* See Hack #1 or #2 for the httpRequest(  ) code sample and the associated function initReq(  ). They are snipped here for the sake of brevity. */ function calcTotal(price){     return stripExtraNumbers(numberOfShares * price); } /* Strip any characters beyond a scale of four characters  past the decimal point, as in 12.3454678 */ function stripExtraNumbers(num){     //check if the number's already okay     //assume a whole number is valid     var n2 = num.toString(  );     if(n2.indexOf(".") == -1)  { return num; }     //if it has numbers after the decimal point,     //limit the number of digits after the decimal point to 4     //we use parseFloat if strings are passed into the method     if(typeof num == "string"){         num = parseFloat(num).toFixed(4);     } else {         num = num.toFixed(4);     }     //strip any extra zeros     return parseFloat(num.toString(  ).replace(/0*$/,"")); } function displayMsg(div,bdyText,txtColor){     //reset DIV content     div.innerHTML="";     div.style.backgroundColor="yellow";     div.style.color=txtColor;     div.innerHTML=bdyText; }

All the number crunching starts in the call to handleResponse( ). First, the code receives the response as a string, in var stockPrice = request.responseText. The code then tests the validity of the stockPrice variable using a method that is part of JavaScript's core API: isNaN( ). This is the best way to test whether a string value in JavaScript can represent a valid number. For example, isNaN("goodbye") returns TRue because "goodbye" cannot be converted to a number. The code also tests the number of shares value with this function.

If either method returns true, indicating an invalid number value, the code throws an exception. This is another way of declaring, "We can't use these values; get them out of here!" The web page then displays an error message to the user.

Exception handling with Ajax is covered in "Handle Request Object Errors" [Hack #8].


However, we're not yet finished with our number crunching. The calcTotal( ) function then multiplies the share total by the stock price in order to display the total value to the user.

To make sure that the numerical display of the value is friendly enough to the eye (in terms of the U.S. stock exchange), the stripExtraNumbers( ) function keeps no more than four characters to the right of the decimal point.

Even though $10.9876 may look a little weird (stock prices are sometimes displayed with four or more characters to the right of the decimal point), I decided to allow this display for the total share value.


DOM-inating

The code uses Document Object Model programming to dynamically display new text and values on the page, all without having to make new server calls and refresh the entire page. The following bit of code, within the handleResponse( ) function, calls the displayMsg( ) function to show the user the total share value. The code also dynamically embeds the stock price just to the right of the text field where the user entered the stock symbol. All the code does here is get a reference to the div element with id stPrice, make its font-size style property a little smaller than the web user's font setting, and then set the div's innerHTML property:

displayMsg(document.getElementById("msgDisplay"),info,"black"); document.getElementById("stPrice").style.fontSize="0.9em"; document.getElementById("stPrice").innerHTML ="price: "+stockPrice;

The displayMsg( ) function is also simple. It has a parameter that represents the font color, which allows the code to set the font color "red" for error messages:

function displayMsg(div,bdyText,txtColor){     //reset DIV content     div.innerHTML="";     div.style.backgroundColor="yellow";     div.style.color=txtColor;     div.innerHTML=bdyText; }

Figure 1-7 shows what the page looks like when the user requests a stock value.

Figure 1-7. Tallying your investment


Figure 1-8 shows an example error message, in case the user enters values that cannot be used as numbers or the server returns invalid values.

Figure 1-8. Having a bad number day





Ajax Hacks
Ajax Hacks: Tips & Tools for Creating Responsive Web Sites
ISBN: 0596101694
EAN: 2147483647
Year: 2006
Pages: 138

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net