Hack 5. Get Plain Old Strings


Manage weather readings, stock quotes, web page scrapings, or similar non-XML data as plain old strings.

The request object has the perfect property for web applications that do not have to handle server return values as XML: request.responseText. This hack asks the user to choose a stock symbol, and the server returns the stock price for display. The code handles the return value as a string.

A variation to this program in the next hack requires the stock prices to be handled as numbers. These are old prices that a server component stores for certain stock symbols, not live quotes that you would obtain from a commercial web service or by HTML scraping. For an example of that mechanism, see "Use XMLHttpRequest to Scrape a Energy Price from a Web Page" [Hack #39].


First, here is the HTML for the web page. It imports JavaScript code from a file named hack9.js:

<!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/js/hack9.js"></script>     <meta http-equiv="content-type" content="text/html; charset=utf-8" />     <title>Choose a stock</title> </head> <body> <h3>Stock prices</h3> <form action="javascript:void%200" onsubmit=         "getStockPrice(this.stSymbol.value);return false">     <p>Enter stock symbol: <input type="text" name=             "stSymbol" size="4"><span ></span></p>     <p><button type="submit">Get Stock Price</button></p> </form> </body> </html>

Figure 1-5 shows the web page as displayed in Firefox. The user enters a symbol such as "GRMN" (case insensitive) and clicks the Get Stock Price button; the JavaScript then fetches the associated stock price and displays it within a span element to the right of the text field.

Figure 1-5. Instantaneously displaying a stock price


The function that sets the request process in motion is getStockPrice( ). This function takes the value of the text field named stSymbol and returns the associated stock price (it uses the request object to talk to a server component, which fetches the actual stock price). Here is the JavaScript code:

var request; var symbol;   //will hold the stock symbol function getStockPrice(sym){     symbol=sym;     if(sym){         var url="http://localhost:8080/parkerriver/s/stocks?symbol="+sym;         httpRequest("GET",url,true);       } } //event handler for XMLHttpRequest function handleResponse(  ){     if(request.readyState == 4){         if(request.status == 200){             /* Grab the result as a string */             var stockPrice = request.responseText;             var info = "&#171;The  price is: $"+stockPrice+"&#187;";             document.getElementById("stPrice").style.fontSize="0.9em";             document.getElementById("stPrice").style.             backgroundColor="yellow";             document.getElementById("stPrice").innerHTML=info;                      } else {             alert("A problem occurred with communicating between "+                   "the XMLHttpRequest object and the server program.");         }     }//end outer if } /* See Hack #1 for the httpRequest(  ) code; it is snipped here for the sake of brevity. */

The function getStockPrice( ) wraps a call to the function httpRequest( ), which is responsible for setting up the request object. If you have already read through some of this chapter's other hacks, you will recognize the handleResponse( ) function as enclosing much of the interesting action.

"Detect Browser Compatibility with the Request Object" [Hack #1] and "Use Your Own Library for XMLHttpRequest" [Hack #3] explain the httpRequest( ) function in more detail.


If the request is complete (i.e., if request.readyState has a value of 4) and the HTTP response status is 200 (meaning that the request has succeeded), the code grabs the server response as the request.responseText property value. The code then uses DOM scripting to display the stock price with some CSS style-related attributes:

document.getElementById("stPrice").style.fontSize="0.9em"; document.getElementById("stPrice").style.backgroundColor="yellow"; document.getElementById("stPrice").innerHTML =info;

The style attributes make the font size a little bit smaller than the user's preferred browser font size and specify yellow as the background color of the text display. The innerHtml property of the span element is set to the stock price within double angle brackets.




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