Section 1.10. Checking for the right ready state


1.10. Checking for the right ready state

You already know that the browser will run your updatePage() function when it gets a response from the server. But, there's a twist: the browser actually runs updatePage()every time the ready state changes, and not just when the server is finished sending back a response. Look at the diagram on page 54 again, and notice that as the request is progressing, the ready state number changes.

It looks like when the server is finished with our request, the ready state is "4", so we can check for that number in our code. That way, we can make sure that we only try and update Katie's report when we know that the server has sent us back a response.

     function updatePage() { This function will get run every time the ready state changes. readyState is the property on the request object that stores the current ready state. When the request object's readyState is set to   4, the server is done wit the request.       if (request.readyState == 4) {      var newTotal = request.responseText; All this code only runs when the request's ready state is 4, and the server's done with the reqest.       var boardsSoldEl = document.getElementById("boards-sold");       var cashEl = document.getElementById("cash");       replaceText(boardsSoldEl, newTotal);       /* Figure out how much cash Katie has made */       ... Here's that code you wrote a few pages back.       /* Update the cash total on the web form */       ...       } Don't forget the closing bracket.     } 

When the server is finished with your request, the ready state of the request will be "4" ... that means that it's safe to use the data that the server sent back (and that the browser stored in your request object).

The server is returning the new sales numbers, which the PHP script figured out.




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