|
| 1 | +import Link from 'next/link' |
| 2 | +import styles from '../styles/Home.module.css' |
| 3 | + |
| 4 | +export default function PageWithJSbasedForm() { |
| 5 | + // Handle the submit event on form submit. |
| 6 | + const handleSubmit = async (event) => { |
| 7 | + // Stop the form from submitting and refreshing the page. |
| 8 | + event.preventDefault() |
| 9 | + |
| 10 | + // Get data from the form. |
| 11 | + const data = { |
| 12 | + first: event.target.first.value, |
| 13 | + last: event.target.last.value, |
| 14 | + } |
| 15 | + |
| 16 | + const JSONdata = JSON.stringify(data) |
| 17 | + |
| 18 | + // Send the form data to our API and get a response. |
| 19 | + const response = await fetch('/api/form', { |
| 20 | + // Body of the request is the JSON data we created above. |
| 21 | + body: JSONdata, |
| 22 | + |
| 23 | + // Tell the server we're sending JSON. |
| 24 | + headers: { |
| 25 | + 'Content-Type': 'application/json', |
| 26 | + }, |
| 27 | + // The method is POST because we are sending data. |
| 28 | + method: 'POST', |
| 29 | + }) |
| 30 | + |
| 31 | + // Get the response data from server as JSON. |
| 32 | + // If server returns the name submitted, that means the form works. |
| 33 | + const result = await response.json() |
| 34 | + alert(`Is this your full name: ${result.data}`) |
| 35 | + } |
| 36 | + return ( |
| 37 | + <div className="container"> |
| 38 | + <h1 className={styles.title}> |
| 39 | + Form{' '} |
| 40 | + <Link href="/"> |
| 41 | + <a>with</a> |
| 42 | + </Link>{' '} |
| 43 | + JavaScript. |
| 44 | + </h1> |
| 45 | + |
| 46 | + <p className={styles.description}> |
| 47 | + Get started by looking at{' '} |
| 48 | + <code className={styles.code}>pages/js-from.js</code> |
| 49 | + </p> |
| 50 | + |
| 51 | + <form onSubmit={handleSubmit}> |
| 52 | + <label htmlFor="first">First Name</label> |
| 53 | + <input type="text" id="first" name="first" required /> |
| 54 | + <label htmlFor="last">Last Name</label> |
| 55 | + <input type="text" id="last" name="last" required /> |
| 56 | + |
| 57 | + <button type="submit">Submit</button> |
| 58 | + </form> |
| 59 | + </div> |
| 60 | + ) |
| 61 | +} |
0 commit comments