Previous Page
Next Page

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:

    <script type="text/javascript" src="/parkerriver/js/hack4.js">
    <meta http-equiv="content-type" content="text/html; charset=utf-8" />
    <title>Tally your stocks</title>
<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 id="stPrice"></span></p>
<p>Enter share amount: <input type="text" name="numShares" size="10"></p>
<p><button type="submit">Get Total Value</button></p>
<div id="msgDisplay"></div>

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){
        var url="http://localhost:8080/parkerriver/s/stocks?symbol="+sym;
//event handler for XMLHttpRequest
function handleResponse(  ){
    if(request.readyState == 4){
        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;
                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);
                document.getElementById("stPrice").innerHTML ="price: 
            } catch (err) {
                        "An error occurred: "+
        } else {
                    "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

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.


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:

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

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

Previous Page
Next Page