Start learning free

LESSON 61 OF 161 · FRONTEND: TALKING TO AN API

Project: Place the Order

Practice

The cart works. Now the order form at the bottom of the cart has to send it. A form already knows how to send itself: on submit, the browser sends the form to the page's address and loads a new page. That throws away your page and app.js with it, so no request ever reaches the API.

So you listen for the form's submit event. It fires for a click on the button and for Enter in a field. The first thing the function does is event.preventDefault(), which tells the browser not to send the form itself. For example, on a newsletter form:

function subscribe(event) {
  event.preventDefault();
  console.log("Subscribing " + address.value);
}
newsletterForm.addEventListener("submit", subscribe);

Then the page sends POST /api/orders with the email as JSON, through your api helper. The server answers 201 with { id, total } and empties its cart. Or it answers 400 with a message, and api throws an Error carrying it: show error.message, the server's own words. After an order, the page's cart must be empty too, and drawn again.

The check types an email, clicks, fixes the email, clicks, fills the cart and clicks again:

> click "Place order"  (email: ana@example)
  request: POST /api/orders {"email": "ana@example"} -> 400
  text: A valid email is required
> click "Place order"  (email: ana@example.com, empty cart)
  request: POST /api/orders {"email": "ana@example.com"} -> 400
  text: Your cart is empty
> add the Mug and the Lamp, click "Place order"
  request: POST /api/orders {"email": "ana@example.com"} -> 201
  cart: list (empty), Total: $0
  text: Order 1001 placed, total $41

Your task: in app.js, make the order form call placeOrder on submit. In placeOrder, stop the browser's own submit, send POST /api/orders with the email, show the order's id and total or the server's message in orderMessage, empty cart after an order and draw the page again.


Assignment
Follow the Coding Tutorial to finish placeOrder: listen for the form's submit, send the order with your api helper, show the result or the server's message, and empty the cart on the page.


Hint
Only the lines inside try after the await run when the order is placed: the success message and cart = [] go there. render() goes below the try and catch, so it runs either way.


STEP 1 OF 9
    Ctrl + Enter to check