HTML Refresher

HTML Refresher

Feeling a little rusty on your <div> s and <span> s? We're going to dive into some HTML on the next page, so before we do, here's a quick refresher course on two of the coolest HTML elements you'll ever run across.

A <div> is a container element that can hold related elements, and allow you to style all those elements with one CSS rule.

    <div id="menu">Use a <div> to group together elements with a
similar purpose.
    <a href="home.html">home</a>
      <a href="books.html">writing</a>
      <a href="links.html">resources</a>
      <a href="lib.html">library</a>
    </div>You can refer to a <div>'s id in your CSS to style
everything within the <div> at one time.

<span> lets you separate a bit of inline text from its surroundings. You can style your <span> elements using CSS, and set off text easily.

     <li><span class="cd">Buddha Bar</span>,
      <span class="artist">Claude Challe</span></li><span>
elements can set off text, but don't start new paragraphs or blocks.
     <li><span class="cd">When It Falls</span>,
      <span class="artist">Zero 7</span></li><span> elements
don't create a new block of text, but can still by styled with CSS.

Reviewing the Boards 'R' Us HTML

First things first... Katie already has a web page, so let's take a look at it. Then you can begin to add in all the JavaScript code we've been talking about. Here's what Katie's page looks like so far:

      <title>Boards 'R' Us</title>Katie's read "Head First HTML with CSS
& XHTML", so she's all over this stuff...
      <link rel="stylesheet" type="text/css" href="boards.css" />Katie's using
an external CSS stylesheet.
     </head>You'll need <script> tags here...

      <h1>Boards 'R' Us Sales Report</h1>
      <div id="boards">
        <tr><th>Snowboards Sold</th>
         <td><span id="boards-sold">1012</span>Here's the total
sales figure you'll need to update...
        <tr><th>What I Sell 'em For</th>
         <td>$<span id="price">249.95</span></td></tr>
        <tr><th>What it Costs Me</th>
         <td>$<span id="cost">84.22</span></td></tr>
      <h2>Cash for the Slopes:
       $<span id="cash">167718.76</span>...and then you
can figure out a new net profit, too.
      <form method="GET" action="getUpdatedBoardSales.php">
       <input value="Show Me the Money" type="submit" />Here's that
button Katie pushes for updated totals. Right now, it submits the form, but you're going
to change that soon.

Katie used id attributes on her <span> tags so she could style them in CSS...

...and we can use those IDs later in our JavaScript to update the numbers in each of these <span>s.

Just Do It

It's time to take some action. Download the examples for the book at, and find the chapter01/boards/ folder. Open up the boards.html file in your web browser. It should look just like Katie's page above.

Step 1: Creating a request object

Let's get back to updating Katie's web report. First up, you need a function that creates a new object to make requests to the server. This turns out to be a bit tricky, because different browsers have different ways of creating this object. To help you out, we've written some "pre-assembled" JavaScript for you. Whenever you see the logo, it means you'll have to take some code on faith, like this code below that creates an object to make requests to the server. Trust us thoughyou'll learn all about this code in more detail in the chapters to come. For now, just type it in and see what it can do.

If you don't want to type this in yourself, you can find this code in create-request.txt, in the chapter01/boards examples folder...

    var request = null;Here's a variable to hold the request object.
    function createRequest() {
      try {
        request = new XMLHttpRequest();This line tries to create a new request object.
      } catch (trymicrosoft) {This is the type of the request object.
        try {
          request = new ActiveXObject 
("Msxml2.XMLHTTP");These two lines try and create the
request object, too, but in a way that works on Internet Explorer.
      } catch (othermicrosoft) {
        try {
          request = new ActiveXObject("Microsoft.XMLHTTP");
        } catch (failed) {
          request = null;If something goes wrong, this makes sure the request
variable is still set to null.

    if (request == null)Now, you can check if request is still null. If it is,
something went wrong in the code...
      alert("Error creating request object!");...and we can spit out an error message to
users with JavaScript's alert() function.

...but you should really type this code in yourself. It will help your brain get used to writing and thinking about Ajax apps.

Go ahead and add this code into the <head> element of your HTML in boards.html. Don't forget, you'll need to add the <script> and </script> tags, too.

     <title>Boards 'R' Us</title>
     <link rel="stylesheet" type="text/css" href="boards.css" />
     <script language="javascript" type="text/javascript">These tell the
browser that you're adding some scripting, and that you're using JavaScript as the
scripting language.

     </script>All that pre-assembled JavaScript goes in here.

Frequently Asked Questions?


Am I supposed to understand exactly what that code does yet?


No, you don't need to understand all of this code yet. For now, just get a general idea of how this looks; we'll explain it in detail in Chapter 2.


What is null ? I saw that in the pre-assembled JavaScript, and wasn't sure what that means.


null is a special value, and actually means an empty value, or a nonexistent reference. In other words, it's sort of like an aniti-value. But don't confuse null with "0" or "false"those both are non -empty values, and aren't the same as a null value.


Is the request object called "XMLHttpRequest " or "ActiveXObject "?


It could be either. We'll talk a lot more about this in the next chapter, but the short answer is that you have to use different object names for different types of web browsers.


So do my users have to use a certain browser to use my Ajax apps?


No, as long as your users have JavaScript enabled in their web browser, this code should work without any problems.So your Ajax apps will run just fine on Firefox, Mozilla, Internet Explorer, Safari, Netscape, and Opera.


What if someone has JavaScript disabled in their browser?


Unfortunately, Ajax applications require JavaScript to run. So users who have JavaScript disabled aren't going to be able to use your Ajax applications.

JavaScript is usually enabled in browsers by default, so anyone who has disabled JavaScript probably knows what they're doing, and could turn it back on if they wanted to use your Ajax app.

Step 2: Requesting updated sales

Now that you can get a request object with createRequest(), you're ready for the next step: writing the getBoardsSold() JavaScript function. This function will use the new object to request the total number of boards sold from the server. Let's figure out what this function needs to do, and then we can get back to coding Katie's app. Remember our diagram? Here's the step we're working on:

Here's what you'll need to do to make getBoardsSold() work:

  1. Create a new request object by calling the createRequest() function.

  2. Figure out what URL you need to connect to so you can get updated board sales.

  3. Set up the request object to make a connection.

  4. Request an updated number of boards sold.

You can use the pre-assembled JavaScript from the last two pages to take care of this.

Katie already has this URL in her form, so this should be simple enough.

Here's where you'll use that request object you created in createRequest().

You can use this number later, in Step 3, when you update the page with new values. You'll tackle this in just a little while.

Just Do It

Open up your boards.html file, and add a new JavaScript function called getBoardsSold(), right after createRequest() . Then, see if you can add a line of JavaScript in getBoardsSold() to create a new request object (that's Step "a" from above). If you're stuck, check the answers in the back of this chapter, on page 61.

Be sure and make these changes to your copy of boards.html before you go to the next page.

Adding the getBoardsSold() function

If you did the exercise on the previous page, you should have some code in your boards.html page that looks something like this:

    <script language="javascript" type="text/javascript">Remember, all of the
JavaScript code is between the <script> and </script> tags.
      var request = null;This is your request variable; once your code calls
createRequest(), this variable will point to a new request object.

      function createRequest() {Here's createRequest(), which you should have
added a few pages back.
        // pre-assembled JavaScript

      function getBoardsSold() {This is the new JavaScript function...
        createRequest();...and here's where the request object is created, using
the pre-assembled JavaScript.

Sending the request to the right URL

So what's next? You've got an object that you can use to request the board sales from the server, but how do you make that request? First, you need to tell the object where to send the requestin other words, it needs to know what program on Katie's server to send the request to. So you need to tell it the URL of the script running on the web server. And where do we get that URL? You can find it in Katie's web form:

And where do we get that URL? You can find it in Katie's web form:

    <form method="GET" action="getUpdatedBoardSales.php">Here's
the URL of the PHP script we need to make a request to.
      <input value="Show Me the Money" type="submit" />
    </form>Here's the <form> part of Katie's web report HTML.

But doesn't the PHP script return a bunch of HTML right now? I thought we only wanted the number of boards sold for the Ajax version of the app.

This is bonus credit for those of you who are into PHP. If you don't know PHP, it's OK... just take a quick look, and keep going. You don't need to understand this script to learn Ajax or follow the examples in the book.

PHP a glance

Here's a quick look at the PHP that Katie's using for her Boards app. Remember, we're not going to explain how this all works... but here's what's going on when a request is made for updated board sales.


    // Connect to database
    $conn = @mysql_connect("",The first part of the script
makes a connection to the Boards 'R' Us database.
                           "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';
    $from = ' FROM boardsrus';
    $queryResult = @mysql_query($select . $from);
    if (!$queryResult)
      die('Error retrieving total boards sold from database.');
    while ($row = mysql_fetch_array($queryResult)) {This part of the script handles
getting the latest sales totals from the database.
      $totalSold = $row['boardsSold'];
    $price = 249.95;If you wanted, you could store these values in the database, too.
    $cost = 84.22;
    $cashPerBoard = $price - $cost;The amount of profit on each board is figured
out here.
    $cash = $totalSold * $cashPerBoard;


     <head> <title>Boards 'R' Us</title>
      <link rel="stylesheet" type="text/css" href="boards.css" />Here comes
all that HTML we've been talking about...


     <h1>Boards 'R' Us :: Custom Boards Report</h1>

    <div id="boards">
     <table>Lots and lots more HTML output by the PHP script...
      <tr><th>Snowboards Sold</th>
       <td><span id="boards-sold">
     print $totalSold;

       <tr><th>What I Sell 'em For</th>
       <td>$<span id="price">
      print $price;
       <tr><th>What it Costs Me</th>
        <td>$<span id="cost">
    print $cost;
      <h2>Cash for the Slopes:
       $<span id="cash">
      print $cash;
The PHP outputs the values it got from the database along with the HTML for the report.
        <form method="GET" action="getUpdatedBoardSales.php">
          <input value="Show Me the Money" type="submit" />

What the Heck?

All this code does is look up how many boards have been sold, figure out the total cash Katie's made, and then return an HTML form with the updated totals sales and cash figures.

It's also OK if you don't know PHP, or haven't worked with databases before. In just a few pages, we'll give you a version of the script that runs without a database, so you can run Katie's web report for yourself.

 Python   SQL   Java   php   Perl 
 game development   web development   internet   *nix   graphics   hardware 
 telecommunications   C++ 
 Flash   Active Directory   Windows