Adding An Item

Goals

Allow a user to create a new item.

Understand how to make an AJAX request when prompted by a user's action.

Overview

JavaScript allows us to make our web page dynamic, and responsive to
the actions of our users. In this lesson, we'll allow our users to create
a new item for our list, and ask the server to save it to the database.

To do so, we're going to use JavaScript's ability to perform a task when a
user has taken an action on the page. JavaScript refers to these actions as
events, and we can trigger code to run by using an event listener. We will
be using jQuery to accomplish this, as it provides a powerful and readable interface
to respond to user events.

Our code will take the following steps.

When the user loads the page, our code will start listening for when the user
submits the form at the top of the page.

When a user submits the form (by pressing enter), we will prevent the page
from refreshing, which is the normal behavior for a form.

We will make an AJAX request to our server, creating an item with the
description our user just provided.

Refresh the page and try creating an item. An alert should pop up when you try! What
happens after that? why?

Step 2

Before the alert we wrote in the last step, add the following line of code.

event.preventDefault()

Try creating an item again. What changed? Why did it change?

Step 3

Now that we've successfully listened for a form submission and prevented the page from
refreshing, we're going to ask the server to save this item into the database. Remove
the alert that you wrote in step one, and replace it with the following code. replace
'YOUR-LIST-NAME-HERE' with your list's name.

The AJAX process

You've just done something that many JavaScript developers do daily: Use JavaScript
to make a request to a server, and then update the page with the data with which
the server responds. This abstract process is repeated over and over again: