Section 1.7. What the server used to do...


1.7. What the server used to do...

Remember how the non-Ajax version of Katie's report works? Every time a request is made to the PHP script, it has to return the number of boards sold, along with an entirely new HTML page. Flip back a page, and notice that over half the PHP script is just HTML! Here's another look at what's going on:

 getUpdatedBoardSales.php The URL for Katie's script, from her web form. 

 All of the HTML that the server has to return for each request.     <html>      <head>       <title>Boards 'R' Us</title>       <link rel="stylesheet" type="text/css" href="boards.css" />      </head>      <body>       <h1>Boards 'R' Us :: Custom Boards Report</h1>       <div >        <table>         <tr><th>Snowboards Sold</th>          <td><span >1149        </span></td></tr>         <tr><th>What I Sell 'em For</th>          <td>$<span >249.95</span></td></tr>         <tr><th>What it Costs Me</th>          <td>$<span >84.22</span></td></tr>        </table>       <h2>Cash for the Slopes:         $<span >190423.27         </span></h2>         <form method="GET" action="getUpdatedBoardSales.php">         <input value="Show Me the Money" type="submit" />        </form>       </div>      </body>     </html> All of this HTML, and the only thing that changed is the number of boards sold, and the updated cash total!Katie's server, having to deal with a lot of HTML content.. 


1.7.1. What the server should do now

When you're writing Ajax apps, the server doesn't need to send all that HTML back in its response. Since you'll use JavaScript to update the web page, all you need from the server is the raw data. In Katie's app, that means that all we want is the number of boards sold. Then, you can figure out the cash that Katie has made with some simple JavaScript.

 The total number of boards sold. A much happier, stress-free server.     getUpdatedBoardSales-ajax.php The URL to the new, Ajax-ready  version of the PHP.     1149Katie's server doesn't have nearly as much information to send back to her web form. 

That's all the server sends back now? I'll bet my report will run faster with Ajax! I'll have my PHP guy take care of changing the server-side script right away.

PHP ...at a glance

Katie's PHP script got a lot simpler when all it needed to do was return the total number of boards sold. Take a look:

     <?php     // Connect to database     $conn = @mysql_connect("mysql.headfirstlabs.com",                            "secret", "really-secret");     if (!$conn)       die("Error connecting to MySQL: " . mysql_error());Almost everything in the first part of the script is the same as the old version.     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)) {       $totalSold = $row['boardsSold'];     }     echo $totalSold;Now, instead of a bunch of HTML, the script just returns a single number: the number of boards sold.     mysql_close($conn);     ?> 

* Notice that the code figuring out the cash that Katie made went away. Your JavaScript will take care of those calculations now.


Just Do It

It's time to give Katie's PHP script an Ajax upgrade. Open up the examples, and find getUpdatedBoardSales-ajax.php in the chapter01/boards/ directory. This is a version of getUpdatedBoardSales.php that only returns the number of boards sold, without any HTML in the response. It also works without a database, so you don't need to set one up to use this PHP script. Make sure this file is in the same directory as your boards.html file; we'll be using this new version of the script in just a moment.


1.7.2. The new script's URL

Now that you've got a PHP script that only returns the number of boards sold, instead of a bunch of HTML, we just need to make a request to that script. Remember, you want to send your request to the new version of the PHP script, and only returns the sales total, not an entire HTML page.

Store the URL of this new PHP script in a JavaScript variable, like this:

     function getBoardsSold() {Here's your JavaScript function.       createRequest();This takes care of creating the new request object.       var url = "getUpdatedBoardSales-ajax.php";This is the URL of the Ajaxready version of the PHP script.     } 

1.7.3. Initializing the connection

You've got a request object, and a variable with the URL to connect to. Now you just need to tell the request object how to connect to the server, and give it that URL as the address to connect to. Here's how you do that:

 function getBoardsSold() {   createRequest();   var url = "getUpdatedBoardSales-ajax.php"; This line handles initializing the connection, and tells the request object how to connect to the server.   request.open("GET  ", url, true);Here's where you start to use that request object created in the createRequest() function. } 

1.7.4. Let's break that down a bit...

     request.open(The open() method initializes a connection...     "GET",...and then "GET" indicates how to send data to the server.     url,     true);This means that the request should be asynchronous... in other words, this lets JavaScript know that it doesn't need to wait around for a response from the script. Katie's report won't freeze while the server is answering the request. 

These are some pretty advanced concepts. Give yourself a high five if you came up with any of these questions on your own.

Frequently Asked Questions?

Q:

I thought that it was better to use "POST" for web page requests.

A:

POST is usually used when you are sending a server lots of data, or are completing a form submit that involves money, or placing an order. Since we're not sending any data to the PHP script, and there's no purchase being made here. it's easier to use a GET request; we'll look at POST requests a little later on.

Q:

Should I ever use open() to make a synchronous request, and set that last value to "false"?

A:

Sure. Sometimes you don't want the user to be able to keep using your page while the server is answering a request. For instance, if a user is placing an order, you probably don't want to let them do anything else until you confirm that their order was accepted.


The Great Code-Comment Coupling Contest

In an effort to save programmers time and prevent confusion, code fragments are marrying their comment counterparts across the globe, providing love, companionship, and self-documentation for all.

Below, you'll find several lines of Ajax-related JavaScript. Pair each line of code up with the comment that describes what it does.

The Code

     request.open("POST", url, true);     var request = new XMLHttpRequest();     var url = "/servlet/GetMileageServlet";     request.open("GET", url, false); 

Mr. Code......and Mrs. Comment

The Comments

     /* Initialize an asynchronous connection using POST */     /* Initialize a synchronous connection using GET */     /* Create a new variable and assign it the URL to a Java servlet */     /* Create a new object to talk HTTP to a web server */ 


So how's it coming? Are we any closer to getting my web report back online? I'd love to know how many boards I've sold.

1.7.4.1. Remember our checklist for getBoardsSold()?

You're making pretty good progress in your code. Why don't you check off what you've got done?

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

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

  • Set up the request object to make a connection.

  • Request an updated number of boards sold.

The Great Code-Comment Coupling Contest

Did you pair up the happy couples? Make sure you got all of these right, and if not, take your time and figure out what you missed, and why.

Meet the Happy Couples...

     /* Create a new object to talk HTTP to a web server */       var request = new XMLHttpRequest();     /* Create a new variable and assign it the URL to a Java servlet */Remember, this won't work on Internet Explorer!       var url = "/servlet/GetMileageServlet";This is just a simple JavaScript variable.     /* Initialize an asynchronous connection using POST   */       request.open("GET  ", url, false);When this is false, the request will be synchronous...     /* Initialize a synchronous connection using GET */Requests can be sent via GET or POST.       request.open("POST", url, true);...and when it's true, the request is asynchronous. 


Here's our checklist from page 28... only one item left to go.

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

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

  • Set up the request object to make a connection.

  • Request an updated number of boards sold.


We're working on this last task now.

1.7.4.2. Connecting to the web server

All right! You've got a request object, a URL, and your connection is initialized and ready to go. Now you just need to make the connection, and request the updated number of boards sold. To do that, just call send() on the request object:

     function getBoardsSold() {       createRequest();       var url = "getUpdatedBoardSales-ajax.php";       request.open("GET", url, true);       request.send(null  );You're sending the request here...     } ...and this means that you're not sending any data in the request. The script doesn't need any data; it just returns the total board sales, every time it's run. 

Are you kidding me? We did all this work, and you're telling me I'm sending null to the server? This is what you call next generation programming?

The server doesn't need any data.

In this particular app, you don't need to provide the server with any information. Each request to the PHP script asks for the same thing: a single number, the total number of boards that Katie has sold. So you don't need to send the server anything but null in your request.

Remember, null means an "empty value ", which is exactly what you want to send the server: nothing.

Rotate your brain (and this page) a bit, and don't miss this key point.

Asynchronous applications make requests using a JavaScript object, and not a form submit.

1.7.4.3. Reviewing what we've done

We've still got plenty left to do, but let's take a moment to see what's already done. Grab a cup of joe, let your brain relax, and review the first two steps in turning Katie's report into an Ajax-powered app.

This was the original HTML for the Boards 'R' Us app.

...and here's what you did.

  1. Create a new object to make requests to the server

    You added a new function, called createRequest(), that creates a new request object. The code even works on different browsers.

         <html>      <head>This was the original task we had to complete...        <title>Boards 'R' Us</title>       <link rel="stylesheet" type="text/css"       href="boards.css" />           </head>You'll added this JavaScript into the head of your HTML.      <body>        <h1>Boards 'R' Us Sales Report</h1>     JavaScriptcreateRequest() now creates a new request object. 

  2. Write a JavaScript function to request new board sales totals

    You wrote another new function, called getBoardsSold(). This function used createRequest() to create a new request object. Then, you set up a variable pointing to the Ajax version of a PHP script on Katie's server, initialized the connection, and sent the request to the server.

You don't need to submit the form anymore... getBoardsSold() takes care of making the request to the server.

 Clicking "Show Me the Money" runs the getBoardsSold() function now..     Request Total     Boards Sold We've got an Ajax-ready version of the PHP script running on Katie's server now, too. 

Wait a second... doesn't the "Show Me the Money" button still submit the form to the older version of the PHP script? And how does getBoardsSold() get run? I don't think we're done with Step 2 yet...

There are still some missing pieces

We've got to make sure that Katie's web form no longer gets submitted to the non-Ajax version of her PHP script, or she's going to end up with more page reloads, and all our hard work won't be noticed!

And not only that, but we've got to make sure that our new getBoardsSold() function gets called from the web form. It looks like we're definitely not ready to start updating the page yet... but what do we need to do next?

There are two major tasks we still need to take care of; use the space below to write out what you think needs to happen to finish off Step 2.

STOP! Don't go on to the next page until you've written something in these blanks.

1.7.5. Back to the HTML

Do you see what you need to do? When Katie clicks the "Show Me the Money" button, the web form submits everything to the PHP script. But we don't want the web form to get submitted, because we're using Ajax to handle requests to the server. This shouldn't be too hard to fix, though.

Let's go back to the HTML for the Boards 'R' Us report:

     <body>This is just the HTML in the <body> tag... we've left the rest of the file off.      <h1>Boards 'R' Us :: Customer Boards Report</h1>      <div >       <table>        <tr><th>Snowboards Sold</th>         <td><span >1012</span></td></tr>       <tr><th>What I Sell 'em For</th>        <td>$<span >249.95</span></td></tr>       <tr><th>What it Costs Me</th>        <td>$<span >84.22</span></td></tr>       </table>       <h2>Cash for the Slopes:        $<span >167718.76</span></h2>       <form method="GET" action="getUpdatedBoardSales.php">        <input value="Show Me the Money" type="submit" /><input value="Show Me the Money" type="button" />This button shouldn't submit the form anymore...       </form>      </div>     </body> ...so you can change it to be just a normal input button. 

Frequently Asked Questions?

Q:

Couldn't we remove the action from the <form> tag, instead of changing the button type?

A:

That's a good idea, in addition to changing the button type. If you only remove the action, though, the "Show Me the Money" button will still try and submit the form... but with no action on the <form> tag, all you'll get is a page reload. So be sure to also change the button type from "submit" to "button".


1.7.6. Running getBoardsSold() from the web form

The JavaScript's ready, and the button no longer tries to submit the form... but right now, getBoardsSold() never runs, either. This shouldn't be too hard to fix, though:

Can't we just run the getBoardsSold() function whenever someone clicks on "Show Me the Money"?

     <input value="Show Me the Money" type="button" /> Any time this button is clicked...     function getBoardsSold() { ... }...this JavaScript function 

A Question For JavaScript

Q:

JavaScript, we need to run a function from our HTML. Can you help us out?

A:

Oh, well I'm incredibly flexible when it comes to calling functions from a web page. Just use one of my event handlers in your HTML. You can use onBlur () for when someone leaves a field, or onClick (), for when a user clicks... how about onChange (), for when a value changes... or there's onFocus () ... wait, wait, I've got more... what do you mean, out of time?


1.7.7. Adding an event handler

Any time Katie clicks the "Show Me the Money" button, the getBoardsSold() function should run. You can use a JavaScript event handler to take care of this. An event handler connects a piece of JavaScript codelike the getBoardsSold() functionto a certain event, like when someone clicks a button on a web page.

In the Boards app, let's use an event handler to connect the "Show Me the Money" button to the getBoardsSold() function. Since you want to attach the event to a button click, use the onClick handler, like this:

 Since this form should never get submitted in the Ajax version of the report, you can remove the "action" attribute if you want.     <form method="GET" action="getUpdatedBoardSales.php">      <input value="Show Me the Money" type="button"                onClick="getBoardsSold();"/>"onClick" means that anytime Katie clicks this button...     </form> ...this function will get run. 

Reviewing the highlight reel

Remember our highlight reel? Have you been keeping up with what we've covered, and what you've still got to look forward to? Let's take a quick look at what you've learned in this chapter so far:

Asynchronous applications make requests using a JavaScript object, and not a form submit.

Your requests and responses are handled by the web browser, not directly by your JavaScript code.

Once the web browser gets a response to your asynchronous request, it will run a callback function.

We used createRequest() to create this request object.

We haven't gotten to these two concepts yet.

This is why we changed the "Show Me the Money" button to call a JavaScript function, instead of having it submit Katie's web form.


1.7.8. Step 3: Coding updatePage()

So now you've taken care of talking to the server, and you're ready to get the server's response, and update the Boards report with new numbers. It's time to write updatePage() . Remember what this function is supposed to do?

 Now the server's response only has the number of boards sold in it.     Updated Number     of Boards SoldupdatePage() gets the server's response...     Boards     Sold     Cash for     Slopes...and then updates the numbers in the web report. 

BRAIN POWER

How can your updatePage() function get the response from Katie's PHP script? Remember, the request to the script was made in getBoardsSold()... and this is supposed to be an asynchronous application. That means Katie shouldn't have to wait around while the server is getting new sales totals.

So how does updatePage() get the response from the server? Think about this for a minute or two, and then turn the page.


I think we should call the updatePage() function at the end of getBoardsSold(). Then updatePage() can get the response from the server, right?

1.7.8.1. Ajax is asynchronous JavaScript

Remember, getBoardsSold() makes an asynchronous request. That means that the JavaScript doesn't wait around for an answer from the server.

In fact, the getBoardsSold() function will probably finish running before the getUpdatedBoardSales-ajax. php script even has a chance to finish processing your request.

 function getBoardsSold() {  createRequest();  var url =   "getUpdatedBoardSales-ajax.php";  request.open("GET", url, true);  request.send(null);  updatePage(); } This won't work... since send() doesn't wait on a response from the server, updatePage() would run before the server has finished with your request. 

So if getBoardsSold() finishes running before the server responds, where does the response go? And how can we make sure that updatePage() runs when the server's finished with our request?

1.7.8.2. Where does the response go?

You've uncovered the trickiest part of asynchronous web programming: if asynchronous code doesn't wait around for a response from the server, how do we use that response? And where does the server's response go in the first place?

You already know about web pages, which can use event handlers to call JavaScript functions. And you've seen how asynchronous JavaScript can make requests to a web server. To complete the asynchronous picture, though, there's another important piece of the puzzle...

1.7.9. How we see web apps...

To figure out what's going on, we're going to have to step back a bit, and think about web applications in general. When you think about a web appl, you probably think about an HTML page, some JavaScript code, a bit of CSS for style, and maybe a web server running some scripts or a servlet. All these pieces work together, like this:

 The HTML and CSS get combined into what we actually seethe web page.     JavaScriptYou use JavaScript to say what a web page does.     Request     Web ServerThe web server waits on requests, and then sends data back to your web page.PHP scripts, Java servlets, Ruby programs, and other server-side components.     Response     HTMLYou use HTML to say what a web page is...     CSS...and CSS to say how the page should look. 

But there's more going on than meets the eye...

WHO AM I

It's time to test those higher-order thinking skills. There's an important character in the Ajax play that you haven't met yet, and he's ready to make his grand entrance. See if you can upstage this new character by figuring out who he is before you turn the page. We've managed to collect a few quotes from the mystery character to help you out.

"Singing? Well, a lot of people don't realize this, but I am classically trained. And I love Wagner."

"Give me your tired, your poor, your huddled brackets yearning to be styled."

Yes, our mystery character tends to be a bit overly dramatic at times.

"Sure, I love water sports. In fact, I was an extra in 'Point Break', and almost got a lead role in 'Blue Crush'."

"I'm as tough as they come... I've even been involved in a few wars over the years."


Write who you think the mystery character is in this blank, and then turn the page to see if you were right.

1.7.10. Introducing the web browser

Behind the scenes, something has to connect all these pieces together. That "something" is the web browser. The browser takes your HTML and CSS, and turns those angle brackets and semicolons into a page with graphics, buttons, and text.

It's also the web browser that runs your JavaScript code... behind the scenes, the browser takes care of important jobs like storing the values of your variables, creating new types, and handling any network requests that your code might make.

     JavaScriptIt's the browser that stores variable values and gives your code access to network requests and responses.     HTML...and turns them into a visual page that users can see.     CSS     Web BrowserThe web browser takes your HTML and CSS...     Web ServerThe browser also handles making requests to web servers, and figuring out what to do with responses it gets back from those servers.     Internet Explorer     Firefox     Opera     Safari     MozillaWhen you type in a URL, click a button, or enter a value in a field, the browser passes those events on to a JavaScript function or a program on the web server. 

Here's what we've been talking about these last several pages.

So now you're telling me that my code isn't making requests to the server? That it's really the web browser doing all that? I'm so confused...

1.7.10.1. The browser just helps out

The browser isn't doing anything that tricky. When your JavaScript needs to make a request, you write code like this:

     function getBoardsSold() {       createRequest();       var url = "getUpdatedBoardSales-ajax.php";       request.open("GET", url, true);       request.send(null);     } 

All the browser does is handle the low-level network stuff that makes this code work. Since network connections work differently on each operating system (think Linux and Windows and Mac OS X), the browser handles the stuff specific to each system. That way, your JavaScript will work on any systemand the browser takes care of turning your code into something each user's particular computer understands.

Take a look back at page 40, and notice that it's the browser that actually handles sending requests and getting responses from the server. Your code tells the browser what to do, and then the browser takes care of actually doing it.

Your requests and responses are handled by the web browser, not directly by your JavaScript code.

BRAIN POWER

Why do you think it's so important that the web browser handle requests in asynchronous applications? Remember, a web server can only respond to whomever made the original request to that server.


1.7.11. The browser gives the server's response to your JavaScript

Since the browser handles sending requests, it's also responsible for getting responses back from the server. Let's see what the browser is doing in the Boards app:

  1. The browser displays the Boards app to Katie

     Here's what Katie sees.     boards.html     boards.cssHere's what you provide to the web server.     Web BrowserThe browser retrieves the HTML and CSS from the web server...     Internet Explorer     Firefox     Opera     Safari     Mozilla...and turns them into this. 

  2. The browser runs the getBoardsSold() function

         Web BrowserKatie clicks this button...     Internet Explorer     Firefox     Opera     Safari     Mozilla     JavaScript     getBoardsSold()...and the browser sees that onClick   is attached to the getBoardsSold() function. 

  3. The browser runs the createRequest() function

         Web BrowserIt's actually the web browser that is "running" all your JavaScript code.     Internet Explorer     Firefox     Opera     Safari     Mozilla     getBoardsSold()     createRequest()createRequest() counts on the browser to help it create a request object. 

  4. The browser sends a request to Katie's web server

         Number ofThis request comes from the browser, and not directly from your JavaScript code.     Boards Sold     Web BrowserThe browser figures out how to make a request on Katie's system.     Internet Explorer     Firefox     Opera     Safari     Mozilla     JavaScript     PHPScript     getBoardsSold()Your code asks that a request be sent by calling request.send(null)  ;. 

  5. The browser returns "control" to Katie

         Web BrowserThe browser returns control to the user, since you made an asynchronous request...     Internet Explorer     Firefox     Opera     Safari     Mozilla     JavaScript     getBoardsSold() Katie can keep using the report (even though there's not much she can do). At least she isn't staring at a spinning beach ball or an hourglass! 

  6. The browser gets a response from the server

         Number of     Boards Sold     Web BrowserThe script sends its response back to the browser.     Internet Explorer     Firefox     Opera     Safari     Mozilla     PHPScript     ? ? ?So what does the browser do with the response? You'll find out on the next few pages... 

1.7.12. What should the browser do with the server's response ?

The browser gets the response from the server, but won't do anything with that response unless you tell it to. So we need to figure out a way to let the browser know to run our updatePage() function once it gets a response.

     Request TotalThe server gets a request from the browser, based on our code in getBoardsSold()...     Boards Sold     PHP script     Number of...and then the server sends its response back to the web browser.     Boards Sold     Web BrowserThe browser gets the response, but doesn't know what to do with it.     Internet Explorer     Firefox     Opera     Safari     Mozilla     updatePage()Somehow, we need to tell the browser to run updatePage() when it gets a response from the server.     JavaScriptOnce we get the browser to run updatePage(), we can use JavaScript to update the Boards report.     Boards     Sold     Cash forIn just a few pages, you'll learn about how to use the DOM-the Document Object Model-to make changes like this to your web page, all without any page reloads.     Slopes 

Espresso Talk

Tonight's coffee-loving, jittery-handed guests:

Web Browser and an HTML Page Browser

Browser: Hi there, HTML. Good to see you again. I was just talking with your buddy, CSS.

HTML Page: Oh yeah? I've been hanging out with him a lot more these days. It seems people must be reading up on using CSS in their pages... we both love it, though.

Browser: Yeah, I'm a big fan. Although it does mean I have to do some extra work, since I've got to take two files and combine them together.

HTML Page: You have to do work? What do you mean? I'm the one who had to say farewell to old friends like "align" and "font face". I don't see what any of this has to do with you.

Browser: Are you kidding? You markup language types... always in the dark. XHTML is the exact same way... without me, nobody would even see you guys!

HTML Page: What, just because you're the program that lets people look at us? Look, the only reason you even exist is to let people view my markup.

Browser: Boy, you just don't have a clue, do you? People can "see" HTML with a text editor... but nobody cares about your angle brackets and <head> tags. People want what I make out of you... a visual page, with images and tables and links.

HTML Page: Delusions of grandeur... geez. Yeah, I'm sure people are beating down your door to see how many different ways you can display the same web page. Yeah, I just love web browsers, and how they're always screwing up how I look.

Browser: The browser wars are coming to an end, you big uninformed bucket of brackets. Besides, if people would just write standardized web pages, there'd hardly be any problems.

HTML Page: Oh, really? That's not what JavaScript has been telling me. He was just complaining the other day about having to use two different types of objects for making a simple request to a server.

Browser: Hey, two is a lot better than five or six... and with some of the new releases of browsers like Internet Explorer and Mozilla, I'll bet we'll be using just one type of request object before you know it.

HTML Page: You sure seem to think you have all the answers.

Browser: Maybe not all the answers, but I do have all the responses. And that's just one more thing you need me for.

HTML Page: All the responses? What are you talking about?

Browser: Maybe you should ask your friend JavaScript about that. Everyone seems to think that it's web pages and code that make requests...

HTML Page: Exactly!

Browser: ...but it's really me, behind the scenes, making sure that pages look right, requests get sent, and responses are heard. Without me, you'd just be a bunch of funny characters in a text file.

HTML Page: ...grumble...grumble...


Time to go back to getBoardsSold(), now that we've learned a little more about web browsers.

So how do we talk to the browser ? So far, all the code we've written just deals with that JavaScript request object. Wait a second... that's it! Can we use the request object to talk to the browser?

1.7.12.1. Sending instructions to the browser

Remember, we've got to tell the browser what to do with the server's response to our request before we make the request... because once the request is made, getBoardsSold() finishes running, and our JavaScript code won't know what's going on with the request. Fortunately, the request object we've been using has a property just for this purpose:

     function getBoardsSold() {       createRequest()  ;       var url = "getUpdatedBoardSales-ajax.php";       request.open("GET", url, true);       request.onreadystatechange = updatePage;If you put the name of a function here, the browser will run that function when it gets a response from the server.Be sure you set this property before you call send(), or this function won't get run.JavaScript requires that you leave off the parentheses on the function name here.       request.send(null);     } 

     PHP script     Web Browser     Internet Explorer     Firefox     Opera     Safari     Mozilla     Now what     do I do?     request.onreadystatechange = updatePage;The browser checks the request object to see what it should do next...     updatePage()  ...and finds out it should run the updatePage() JavaScript function.     JavaScript 

Frequently Asked Questions?

Q:

The server talks to the browser, the browser talks to the JavaScript, the JavaScript updates our page... I'm lost. Can you run that by me again?

A:

Remember, these are asynchronous requests. When your code tells the browser to send a request to the server, the server has to respond with an answer but your code doesn't wait around to find out what that answer is. So when the server responds, it's left to the web browser to figure out what to do next. Since there's no running code waiting for a response, the browser runs the function you assigned to the request object's onreadystatechange property.

Q:

Remind me again what onreadystatechange is all about? That seems sort of confusing to me.

A:

It's actually not as difficult as it might look. That property just tells the browser that when the request's state changeslike when the PHP script responds to the browserthe browser should call the JavaScript function indicated in the request object. In this case, that's the updatePage function.

Q:

So are there things besides the script finishing up that can result in updatePage() being called?

A:

Yup. Web requests can be in several different "ready states", and each time the ready state changes, updatePage() is called. We'll dig into this much more in the next chapter, so keep this in mind.


Once the web browser gets a response to your asynchronous request, it will "call back" your JavaScript with the server's response.

1.7.13. Getting the server's response

We're finally ready to code updatePage() ... right? Since you've set up the onreadystatechange property of the request object, the web browser will run updatePage() when the server responds to the request. But something's still missing... Getting the server's response updatePage() createRequest() getBoardsSold()

I see how we can get the browser to run updatePage() when the server responds, but what about the data that the server responds with? How do we get access to that in updatePage()?

1.7.13.1. The browser helps out again

You've already seen how to tell the browser to run the updatePage() function when the server responds, but the browserand that request object you've been usingdoes even more to help you out.

Once the browser gets a response from the server, it figures out what to do next by checking the request object's onreadystatechange property. And, since you're going to want the data the server returned, the browser puts that data in another property of the request object: a property called responseText .

So any time you want to figure out what the server returned in its response, just access the request object's responseText property.

In fact, the browser sets quite a few properties on the request object before it runs your JavaScript function. Stay tuned to find out what these other properties do...

You can get the server's response using the responseText property of your JavaScript request object.

Work It Through

You've already seen two of the properties from the request object we've been using. Now it's time to put what you've learned to the test. Below on the left are several properties of a request object, and on the right are descriptions of these properties. See if you can match the property name to its purpose.

     responseText                                     The HTTP status code                                    returned from the server.     readyState                                    The function for the browser to                                    run when the server responds to                                    your request.     onreadystatechange                                    A number indicating what state                                    the request is in: loading, in                                    progress, finished processing, etc.     status                                    The data returned from                                    the server in response to                                    your request. 


You haven't seen some of these properties yet, but go ahead and take a guess at what each does.

1.7.14. Planning the updatePage() function

The browser stores the server's response in the request object, and then runs updatePage() . We're finally ready to start coding this function. Let's see what we need to do:

First: Get the updated number of boards sold

The server returns this number to the browser, and then the browser puts this value in the request object's responseText property:

     function updatePage() {Here's the request object again.       var newTotal = request.responseText;This is the property of the request object that the browser uses to pass on response data from the server.     } 

Second: Get the HTML elements you need to update

There are two elements you have to update: the number of boards sold, and the cash that Katie has made. You can use JavaScript's getElementById() method to grab each of these based on their id attributes.

     function updatePage() {       var newTotal = request.responseText;Assign each element to a variable, so you can easily reference them in your code later.       var boardsSoldEl = document.getElementById("boards-sold");       var cashEl = document.getElementById("cash");document represents the entire HTML page...These are the names of the HTML elements we want to get....and getElementById() finds the element with the ID you pass into the function.     }     <span >1012</span>     <span >167718.76</span>Remember how Katie added id attributes to her <span>   elements so she could style them with CSS? Those same id attributes make it easy to access each of the <span> elements in our JavaScript code. 

Third: Add a reference to Katie's text utilities

Now you're ready to update the total number of snowboards sold. It's going to take a little bit of advanced JavaScript to update the text in those <span> elements. We'll cover these techniques in Chapter 4, when we talk about the Document Object Model, but for now, Katie has some in a JavaScript utility file, called text-utils.js . This file has some handy functions you can use, but you need to let the Boards app know where to find these utilities first. You can add in a reference to Katie's JavaScript utilities using the <script> tag in your HTML, like this:

You can find textutils.js in the chapter01/boards directory of this chapter's examples.

     <head>This is all in the <head> of your HTML page.      <title>Boards 'R' Us</title>      <link rel="stylesheet" type="text/css" href="boards.css" />      <script type="text/javascript" src="/books/2/850/1/html/2/text-utils.js"> </script>Add this line, and then you can use all the utility functions from text-utils.js in your updatePage() function.      <script language="javascript" type="text/javascript">Here's the beginning of all the JavaScript code you've written in this chapter. 

Fourth: Update the report with the updated board sales

The text-utils.js file has a function in it called replaceText() . You can use this utility function to update Katie's report with the new number of boards sold:

All the functions in text-utils.js use the DOM-the Document Object Modelto update a web page on the fly.

     function updatePage() {       var newTotal = request.responseText;       var boardsSoldEl = document.getElementById("boards-sold");       var cashEl = document.getElementById("cash");       replaceText(boardsSoldEl, newTotal);This function is defined in text-utils.js. We'll talk more about these functions later in the book.This is the element whose text will be replaced......and this is the value to replace the text with.When this code runs, the web report will get updated with the new total for board sales.     } 

Just Do It

You're ready to finish up the updatePage() function on your own. Below is the code for updatePage(), but there are plenty of blanks left to be filled in. Try and figure out the code that belongs in each blank, and write in your answers.

Once you think you've got all the code filled in, be sure to compare your answers to ours on the next page.

     function updatePage() {       var newTotal = request.responseText;       var boardsSoldEl = document.getElementById("boards-sold");       var cashEl = document.getElementById("cash");       replaceText(boardsSoldEl, newTotal);       /* Figure out how much cash Katie has made */       var priceEl = document.getElementById("_____________");       var price = getText(___________);       var _________ = document._______________("cost");       var cost = getText(costEl);getText()   is from text-utils.js. It will take any element, and return the text within that element.       var cashPerBoard = ____________ - _________;       var cash = ___________ * ____________;       /* Update the cash for the slopes on the form */       cash = Math.round(cash * 100) / 100;This little trick makes sure that the cash total has only two decimal places, like a normal dollar value.       replaceText(cashEl, _____________);     } 





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