Writing JavaScript to send the request






Writing JavaScript to send the request

Now let's write the JavaScript to send the request to the coffee-making script:

function sendRequest(url) {All this
code should go in your copy of coffee.js.
    request.onreadystatechange = serveDrink;sendRequest() sets up the callback
function for the server response (serveDrink) and sends a GET
request to the URL passed in from
makeFreshCoffee().
    request.open("GET", url, true);
    request.send(null);
}
function orderCoffee() {
    var name = document.getElementById("name").value;
    var beverage = getBeverage();
    var size = getSize();
    var url = "coffeemaker.php?name=" + escape(name) +We'll
write the functions to get the size and beverage requested in just a few pages.
    "&size=" + escape(size) +orderCoffee() builds the request URL,
using the coffeemaker.php script and all
the information it got from the coffee
order form.. It requests the first coffee
maker be used to brew the coffee.
    "&beverage=" + escape(beverage) +
    "&coffeemaker=1";
  sendRequest(url);
}


Now wait just a second. That's it? You completely forgot something-what if the first coffee maker is already brewing coffee? And what about the second coffee maker? When should we use it?

Which coffee maker should we use?

Each coffee maker can only brew one cup at a time, so what if the first coffee maker is already brewing coffee? Somehow we need to find out if the first coffee maker status is "Idle" before we send a new request. If it's busy, we can try the second coffee maker. And if that one's busy... well, then Jim's gonna have to wait a bit for his coffee.

How do you think we can get the status of each coffee maker?

Here's the HTML for the first coffee maker... what do you think we should do?

<div id="coffeemaker1">
    <h2>Coffee Maker #1</h2>
    <p><img src="/img/head-rush-ajax/CoffeeMaker1.gif"
        alt="Coffee Maker #1" /></p>
    <div id="coffeemaker1-status">Idle</div>
    </div>Remember, the second coffee maker HTML is
very similar to this.

BRAIN POWER

How do you think we can find out the status of the coffee makers? And how can we update the status when one is brewing coffee, and when the coffee maker finishes brewing?


Keep thinking about this, and we'll come back to it a little later in the chapter.



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