Section 6.4. Filling that XML prescription


6.4. Filling that XML prescription

Trying to come up with a data format that works for the server, that the browser understands, and that won't have to change if Katie adds another product line or changes the order of items on her report... that's not so easy.

Luckily for us, Dr. Zigmund (as well as that rather impatient girl on the last page) seems to have a solution: XML, the extensible markup language. Using XML, we can come up with a simple response format that is clear, and contains all three updated sales totals.

 This line just identifies this content as XML. It gives the version of XML used... ...and how the XML is encoded. <?xml version="1.0" encoding="utf-8"?> <totals> is the root element... it just serves as a container for the three "sold" elements.     <totals>     <boards-sold>1710</boards-sold> Even if the order of these lines changed, it would still be clear what each number represented.     <boots-sold>315</boots-sold> There's no question as to which number is the board sales, which is the boot sales, and which is the bindings sales.     <bindings-sold>85</bindings-sold> </totals> The server can send back this entire piece of XML as its response. 

Frequently Asked Questions?

Q:

What's so great about XML?

A:

The biggest thing going for XML is that it's a recognized standard. Some folks at the World Wide Web Consortium (or the W3C for short) define what makes XML, well, XML. And since most people agree to abide by the W3C standard, browsers, servers, and programs like PHP scripts can all use XML without wondering what a bracket or a semicolon means.

Q:

I still don't see why it's so bad to just make up our own data format. Wouldn't that be easier?

A:

It might seem that way, but proprietary data formatsformats that you make up for your own usecan really cause a lot of problems. If you don't document them, people forget how they work. Even worse, some of the characters you might use, like a semicolon or comma, can have more than one meaning, and they make the format confusing to programmers.

Q:

I get why we should use XML, but do we have to use the same element names you did?

A:

No, not at all. That's the beauty of XML: it's flexible. So you might use boardSales instead of boardsales, or totalBindings instead of bindingSales. It's really up to you. As long as both the JavaScript in your browser and the code on your server know what names to use, what those names actually are is really up to you.


PHP ...at a glance

While you've been thinking about Katie's JavaScript and HTML, her server-side guys have been listening in. They've gone ahead and updated the getUpdatedSales.php script to return the XML we've been talking about, complete with updated totals for board, boot, and binding sales. Not too bad, huh? Here's what the script looks like now:

A lot of this is the same as when Boards 'R' Us had just one product, and wasn't using XML.

     <?php     // Connect to database     $conn = @mysql_connect("mysql.headfirstlabs.com",                            "secret", "really-secret");     if (!$conn)          die("Error connecting to MySQL: " . mysql_error());     if (!mysql_select_db("headfirst", $conn))          die("Error selecting Head First database: " . mysql_error());     $select = 'SELECT boardsSold, bootsSold, bindingsSold'; The Boards 'R' Us database now keeps up with three products: boards, boots, and bindings.     $from = ' FROM boardsrus';     $queryResult = @mysql_query($select . $from);     if (!$queryResult)         die('Error retrieving total boards sold from database.');     while ($row = mysql_fetch_array($queryResult)) {         $boardsSold = $row['boardsSold']; In this version of the app, we're interested in three values, instead of just one.         $bootsSold = $row['bootsSold']; This tells the browser that the script is returning XML, not HTML markup or text.         $bindingsSold = $row['bindingsSold'];     }     header("Content-Type: text/xml");     echo "<?xml version=\"1.0\" encoding=\"utf-8\"?> Since the first part of this line, <?, is a start tag in PHP, you have to echo this line out using "echo", separate from the rest of the XML output.     ?> <totals>     <boards-sold><? echo $boardsSold; ?></boards-sold>     <boots-sold><? echo $bootsSold; ?></boots-sold>     <bindings-sold><? echo $bindingsSold; ?></bindings-sold> </totals> Each XML element has the sales number for the related product, from the Boards 'R' Us database query.     <? mysql_close($conn); 


Just Do It

Enough talk; it's time to take action. Open up the chapter06/boards folder in the examples you downloaded from http://www.headfirstlabs.com. You'll see the files for the Boards 'R' Us app, including an updated HTML report (boards.html), several JavaScript files (ajax.js and boards.js), and the XML version of getUpdatedSales.php. Your job is to update the code in the report to get the XML response from getUpdatedSales.php.

Open up boards.js, and find the function that gets the server's response. For now, go ahead and comment out all the DOM code that updates the form... we'll fix that up in a few pages. For now, you want to check the request's ready state, make sure the status code is 200 (meaning everything is OK with the response), and then show the server's response in a JavaScript alert box. Once you're done, you should be able to reload boards.html, click "Show Me the Money", and get something back that looks like this:

The alert box shows the server's response, which is now pure XML. This is what you want to see on your own screen.

Did you figure out how to display the server's response? Here's what we did:

  1. We opened up boards.js, since that has the Boards 'R' Us callback function.

  2. We found the callback, updatePage(), and commented out everything except for the two if statements that checked the ready state and the status code from the request.

  3. We got the server's response, and then used the JavaScript alert() function to show it to the user.

Here's our code for updatePage():

 function updatePage() { Leave the ready state and status checking code alonewe still need that.   if (request.readyState == 4) {     if (request.status == 200) {       var response = request.responseText;       alert(response); This just gets the response from the server, and shows it with an alert dialog box.  /*      var newTotal = request.responseText;      ...      replaceText(cashEl, cash); You should have lots of code in here... comment all that out for now. */     } else {        // Error handling code here     } } 





Head Rush Ajax
Head Rush Ajax (Head First)
ISBN: 0596102259
EAN: 2147483647
Year: 2004
Pages: 241

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