Interactive sites

Many Web pages are static. Users can’t interact with them, except for clicking on links.

Some Web pages are interactive, like the page you’re reading now. You can expand and collapse items in the menu to the right. You can move the mouse over the tabs at the top of the page, and they jump around a little.

Other CoreDogs pages let you type in solutions to exercises. The solutions are saved. They’ll be there next time you look at the page.

In this chapter, we’ll look at how Webers make pages interactive.

Programs in browsers

Where are we?

This chapter is about interactive pages. We’ll start off with programs that run in Web browsers.

This lesson’s goals

By the end of this lesson, you should know:

  • Some programs run inside browsers.
  • Those programs are downloaded along with pages.
  • Every major browser can run JavaScript programs.
  • Programs are triggered by events.
  • JavaScript is used for interface effects, validating form data, input widgets, and sending data to a server.

Example: How many dogs?

Here’s a program that advises humans how many dogs they should live with. Type a number in the input field, and click the button.

How many dogs live in your house?

  

The program is something like this:

When the user clicks the Advice button:
  Get the number of dogs the user entered.
  If it isn't a valid number, show an error message.
  If dogs = 0:
    Show: That's too bad. You should get some dogs.
  If dogs = 1:
    Show: That's not enough dogs. Get another one.
  If dogs = 2:
    Show: That's a good number of dogs to have.
  If dogs is more than 2:
    Show: Lucky you, to live with so many dogs!

Figure 1. How many dogs?

The program doesn’t actually look like this. But Figure 1 shows you the logic behind it. Type in different things, and track through the code in Figure 1 to predict how the program will respond.

How does the program get to the browser? The program is inside the page itself. When I was typing the page you’re looking at right now, I typed the program straight into the page.

So when your browser loaded this page, it loaded the program as well.

JavaScript

The program is in a language called JavaScript. Every major browser can run programs written in JavaScript. So it’s the browser itself that runs the code.

Here’s another example. This one is real JavaScript code. It computes the area of a rectangle.

w = prompt("Width of rectangle?");
h = prompt("Height of rectangle?");
a = w * h;
alert("Area: " + a);

Figure 2. Area program

prompt() shows a dialog like this:

Prompt dialog

Figure 3. prompt() dialog

Then it waits for you to type a number. Line 1 stores whatever you type into the variable w. A variable is a piece of computer memory with a name, like w, sales_tax, or age.

Line 2 gets a value for h. Line 3 computes the area; * means multiply. Line 4 shows the result. alert() shows a message on the screen.

Click the button below to run the program.

Renata
Renata

I typed a negative number into the program, and it didn’t give me an error message. It just gave me a negative area. That doesn’t make sense.

Kieran
Kieran

Computers do exactly what you tell them, and nothing more. There’s no code in Figure 2 to check for negative numbers. The program for Figure 1 does check, but only because I typed in JavaScript code to do that.

CC
CC

What would the check for the width be?

Kieran
Kieran

It would be something like this:

if (w < 0) {
   alert("Please enter a valid width.");
   return;
}

This would go in after line 1 in Figure 2. The return statement stops the program.

I don’t want to go into more detail right now. I just want you to get the general idea of what JavaScript is.

The code in Figure 2 is tied to an event. An event is something that happens in the browser, like a user pressing a key on the keyboard, or moving the mouse over something. The program in Figure 2 is tied to the click event of the button. So when the user clicks the Click me button, the browser runs the code.

What JavaScript is used for

JavaScript is used for lots of things, but the four main ones are:

  • Interface effects.
  • Validating form data.
  • Input widgets.
  • Sending data to a server.

Interface effects

Move your mouse over the dog.

W00fer

That’s a simple interface effect.

I started by making two versions of the dog image. Here they are with borders, so you can tell where the edges are.

No w00f W00f

Figure 5. no-w00f.png and w00f.png

The code is like this:

Initialize the image to no-w00f.png.
When the mouse cursor enters the image:
  Switch the image to w00f.png.
When the mouse cursor leaves the image:
  Switch the image to no-w00f.png.

Figure 6. W00fing

“Initialize” in line 1 means “do this at the start.” So the image starts off as the no-w00f.png version.

The “mouse cursor” in line 2 is the mouse pointer thing you move around the screen. It’s usually an arrow. Line 2 is an event: the mouse cursor moves over the image. When that event happens, the browser runs line 3, and switches the image to the w00f.png version. Lines 4 and 5 switch it back when the mouse leaves the image.

This isn’t a useful interface effect, just a simple example. A more useful effect is the book and chapter expand/collapse in the Lessons menu in the right-hand column.

Validating form data

You’ve filled in lots of forms on the Web. Sometimes you get error messages, telling you you’ve forgotten to complete a field, or done something else the page doesn’t like. JavaScript is used for that.

Here’s a simple one. Give it a try.

The code looks roughly like this:

age = (get what the user typed);
if ( age is empty ) {
  alert('Please enter your age.');
}
else if ( age is not a number ) {
  alert('Please enter a number.');
}
else if ( age < 0 ) {
  alert('Please enter a positive number.');
}
else if ( age > 100 ) {
  alert('Please enter your real age.');
}
else {
  alert('Thank you!');
}

Figure 7. Validating age

Type different things in the field. You should be able to follow the code, and predict what the program will say.

Input widgets

An input widget is a thing on the screen that lets users enter data. You’ve seen two input widgets already:

A text box:

These are built in to HTML. Browsers already know how to make text boxes and buttons. Just give them the right tags on a Web page. For example, here’s what I typed to make the button:

<button type="button">A button</button>

But there are other input widgets that HTML doesn’t have built in. One is called a spin button. Give this one a try.

How many walks would you like today (0 to 5)?
1
Up
Down

Click the up and down arrows, and watch what happens.

HTML doesn’t have a spinner widget built in. I created it, with help from JavaScript.

Send data to a server

You can use JavaScript to send data to a server. This technique is often called Ajax. Once the data gets to the server, it can be stored, emailed, or whatever.

Here’s a simple example. When you click the button below,
a counter on the server goes up by one. Try it.

Number:         Wait...

Here’s how it works. When you click the button, your browser sends a message to the CoreDogs server:

Browser to server: Dude! Increase the counter by one.

The server will do it, and send a message back to the browser.

Server to browser: Done, dude! Here’s the counter’s new value: xxxx.

The counter is stored on the server, not the browser. So if you go to another page and then come back to this one, the counter will retain its data. Shut down your browser, start another one, and the counter will have the same value.

OK – turn your computer off, go to bed, dream of chasing rabbits, wake up tomorrow, fly to Bruges in Belgium, find a computer in an Internet cafe that allows dogs, and look at this page – the counter will still have the right value.

Because the data is on the server, you can shut your computer down, dig a hole and bury it, whatever. The data will remain intact.

And the number goes up when anyone clicks a button, not just you. Have a contest with a dog in Australia. See who can click the button more times in three minutes.

See the little blue thing that appeared briefly? It’s called a throbber. It shows that your browser is contacting the server. The throbber goes away when the server replies.

This is not the only way to send data from a browser to a server. Traditional Web forms don’t use JavaScript to send data. Ajax (using JavaScript to send data) is a relatively new and advanced technique.

Summary

  • Some programs run inside browsers.
  • Those programs are downloaded along with pages.
  • Every major browser can run JavaScript programs.
  • Programs are triggered by events.
  • JavaScript is used for interface effects, validating form data, input widgets, and sending data to a server.

What now?

You’ve seen how browsers run JavaScript programs. But servers run programs as well. Let’s talk about that next.

Programs on servers

Where are we?

This chapter is on interactive Web sites. We just saw how code running in a browser can interact with the user. But that’s just part of the story. Let’s look at the server side.

This lesson’s goals

By the end of this lesson, you will:

  • See how to manually create a Web page with a product list.
  • See how easy it is to make a mistake.
  • Learn that a Web server can automatically create a product list page from data in a database. This reduces the number of mistakes.
Jesse
Jesse

A list of products

Think back to the first chapter of this book, the one about what makes a Web site good. We talked about Jesse and his site, WanderingDog.Com. WanderingDog sells portable electronics for dogs, like MP3 players, and paw-held games.

Here’s part of a page on the site. It lists squirrel scanners people can buy.

SquirelScan 3000 $49.95

Bob's Bark 'n Bag Mark II $54.95

Tree Ratter Xtreme $29.95


Figure 1. Product list

OK, it won’t win any design awards. But it’s simple.

Each product has two pieces of information: name, and price. Each line in the product list has the same format. First the name, then the price in bold.

Here’s the HTML that makes the product list. It’s in a file called squirrel-scanners.html.

<p>
  SquirelScan 3000
  <strong>$49.95</strong>
</p>
<p>
  Bob's Bark 'n Bag Mark II
  <strong>$54.95</strong>
</p>
<p>
  Tree Ratter Xtreme
  <strong>$29.95</strong>
</p>

Figure 2. HTML for product list

The <p> tag makes a paragraph. That’s some content with white space above and below it. The <strong> tag does the bolding.

So every product has a simple HTML template:

<p>
  Name
  <strong>Price</strong>
</p>

Figure 3. HTML template for product list

Apply the template to every product, and you get the HTML for the product list.

Creating the product list

How does the HTML in Figure 2 get created? One way is to do it by hand. Suppose Jesse uses a word processor like OpenOffice Writer or Microsoft Word. He makes a document like this:

Name Price
SquirelScan 3000 $49.95
Bob’s Bark ‘n Bag Mark II $54.95
Tree Ratter Xtreme $29.95

Figure 4. Master product list

Jesse keeps this master product list current at all times.

It’s easy to make the HTML from this. Just a lot of copy-and-paste.

  • Create a new file, called squirrel-scanners.html.
  • Paste a copy of template (Figure 3) at the end of the file. Remember that it looks like this:
<p>
  Name
  <strong>Price</strong>
</p>

Figure 3 (again). HTML template for product list

  • Take the name and price of the first product, and paste them in the copy of the template.
  • Paste another copy of template at the end of the file.
  • Take the name and price of the second product, and paste them in the copy of the template.
  • Paste another copy of template at the end of the file.
  • Take the name and price of the third product, and paste them in the copy of the template.

And so on. Just do the same thing for every product in the master list, and you’ve got the HTML you need. Here it is again:

<p>
  SquirelScan 3000
  <strong>$49.95</strong>
</p>
<p>
  Bob's Bark 'n Bag Mark II
  <strong>$54.95</strong>
</p>
<p>
  Tree Ratter Xtreme
  <strong>$29.95</strong>
</p>

Figure 2 (again). HTML for product list

Jesse uploads squirrel-scanners.html to his Web server. Customers can see it at http://wanderingdog.com/squirrel-scanners.html.

Updating product data

Product data changes all the time. New products are added. Old ones are dropped. Prices go up. Or down, when there’s a sale. There could be dozens of changes a week for a small store with a few hundred products. A large store with thousands of products might have to make a hundred changes to the product data every week.

Suppose the price of Bob’s Bark ‘n Bag Mark II goes from $54.95 to $56.95. Jess first goes to his master product list and changes it:

Name Price
SquirelScan 3000 $49.95
Bob’s Bark ‘n Bag Mark II $54.95 $56.95
Tree Ratter Xtreme $29.95

Figure 5. New master product list

Then Jesse can change the HTML in squirrel-scanners.html. If this product’s price appears on more than one page, Jesse has to remember to change it everywhere.

Let’s say there are 15 price changes per week. That means 15 changes to the master product list, and 15 to the squirrel-scanners.html. That’s 30 changes every week.

It would be easy to make a mistake. Take the price change for Bob’s Bark ‘n Bag Mark II. Let’s say that Jesse typed the new price correctly into the master product list, but made a mistake when editing squirrel-scanners.html. Instead of changing $54.95 to $56.95, he accidentally deleted the first 5, making the price on the Web site $6.95.

Suppose there are ten orders before Jesse finds the mistake. He either loses $50 per order, or annoys ten customers. No way to win.

The more products there are, the more chances there are for errors. Not to mention the time it would take to make all the changes.

A better way

Jesse makes two big changes. First, instead of having his master product list in a word processing document, he puts it into a database table.

A database management system (DBMS) is a piece of software that can help with problems like Jesse’s. There are many different DBMS. Jesse uses MySQL, a popular open source DBMS, widely used for Web sites. CoreDogs uses MySQL underneath.

Most DBMS store data in tables. Here’s a MySQL table called products.

products table from database

Figure 6. products table from database

It’s the same data as before, in more-or-less the same format. There are rows, and there are columns. Each row is data for one product. Each column is an attribute, or characteristic, of a product.

Why did Jesse move the data into a database table? Because when the data is in a database, programs can use the data.

So that’s the first thing Jesse does. He moves the data to a database.

The second thing: he writes a program to automatically create the page squirrel-scanners.html.

Remember the steps Jesse went through to make squirrel-scanners.html manually. Here they are again.

  • Create a new file, called squirrel-scanners.html.
  • Paste a copy of the HTML template at the end of the file.
  • Take the name and price of the first product, and paste them in the copy of the template.
  • Paste another copy of template at the end of the file.
  • Take the name and price of the second product, and paste them in the copy of the template.
  • Paste another copy of template at the end of the file.
  • Take the name and price of the third product, and paste them in the copy of the template.

These are repetitive things that a computer can do. Here’s what a program to create squirrel-scanners.html would do.

Connect to the database.
Open the products table.
For each row:
  Get the name from the row.
  Get the price from the row.
  Output: <p>
            name
            <strong>price</strong>
          </p>

Figure 7. A program to make the product list HTML

Line 3 starts a loop. Lines 4 to 9 run for each row in the table. They grab product data, populate the template, and output the results. When the program finishes, we have this:

<p>
  SquirelScan 3000
  <strong>$49.95</strong>
</p>
<p>
  Bob's Bark 'n Bag Mark II
  <strong>$54.95</strong>
</p>
<p>
  Tree Ratter Xtreme
  <strong>$29.95</strong>
</p>

Figure 2 (again). HTML for product list

It’s the same as before, but the computer does the work, not Jesse.

The big advantage is that Jesse enters a new price just one time, no matter how many times the price is shown on his site. The computer does the grunt work of transforming the product data into HTML, so there are fewer mistakes.

Big productivity win for Jesse! W00f!

Where does the program run?

So there’s a program that takes data from a database, and outputs HTML. Where does the program run? In a browser?

Typically, programs like this run on the Web server, not in the browser. They aren’t written in JavaScript, but in a language designed for use on servers. PHP is a popular server-side language. In fact, the code that generates CoreDogs pages is in PHP.

Here’s what happens.

Showing the product list

Figure 8. Showing the product list

Customers like Sarah and Paula go to the page http://wanderingdog.com/squirrel-scanners.php. The extension isn’t .html anymore, because this isn’t an HTML file. squirrel-scanners.php is a program that generates HTML.

When the Web server gets the request, it notices the .php extension. It runs the program, and sends back the output the program generates.

Remember that squirrel-scanners.php is a program, and it outputs HTML (see Figure 7). So the browser gets HTML. The browser doesn’t know or care that the HTML was generated automatically, rather than typed by a person. It just renders what it gets.

Where the value is

Companies that create value on the Web do a lot of server-side processing. When you send a tweet, a program on a Twitter server stores it in a database. When one of your followers logs in to Twitter, another program reads the database, and shows your tweet.

When you add something to your Facebook wall, a program on a Facebook server stores your new entry in a database. When one of your friends logs in, a different program runs. It extracts your entry from the database, and shows it.

You search for a product on Amazon:

Amazon search

Figure 9. Amazon search

A program runs on an Amazon server. It searches through the database for your search term, and shows matches:

Amazon search results

Figure 10. Amazon search results

Notice that this is like Jesse’s product list, with a product name and a price. Well, a little better, even Jesse would admit that.

So the server side is where it’s at if you want to make money on the Web. CoreDogs’ ServerCore book is all about server-side processing.

Summary

You learned:

  • How to manually create a Web page with a product list.
  • How easy it is to make a mistake.
  • A Web server can automatically create a product list page from data in a database. This reduces the number of mistakes.