5.13. Break Neck error handlingNow that you know how to get a response header from the server, you can improve the Break Neck JavaScript, and let customers know a little more about any errors they run into. Let's make a few simple changes to pizza.js: function showConfirmation() { if (request.readyState == 4) { if (request.status == 200) {If placeOrder.php reports an error, the status code will be "400", so the "else" part of this code will run. var response = request.responseText; var mainDiv = document.getElementById("main-page"); var orderForm = document.getElementById("order-form"); pElement = document.createElement("p"); textNode = document.createTextNode( "Your order should arrive within " + response + " minutes. Enjoy your pizza!"); pElement.appendChild(textNode); mainDiv.replaceChild(pElement, orderForm); } else { var message = request.getResponseHeader("Status");This gets the value of the "Status" response header, if there is one. if ((message.length == null) || (message.length <= 0)) {If there's no "Status" response header, then just print out the error code, like we did in the older versions of the Break Neck app. alert("Error! Request status is " + request.status); } else { alert(message);If the server or script returned a "Status" response header, then show that to the customer. } } } } OK, so now we're ready to go, right?
|