March 2, 2026 — Slides: AJAX
method: GET appends data as query parameters, POST includes data in the request body<form method="GET" action="/signup">
<label for="unameBox">Name:</label>
<input type="text" name="username" id="unameBox">
<button type="submit">Sign up!</button>
</form>
// GET submits as: /signup?username=value
XMLHttpRequest object is verbose and complicated — use fetch() insteadfetch(url) sends an HTTP request and returns a Promisefetch(url); // sends request, returns a Promise
// next line runs immediately (doesn't wait)
.then() with a callback to handle the fulfilled valueresponse.json() parses the response body as JSON — but returns another Promise.then() returns a Promise, you can chain another .then()fetch(url)
.then((response) => {
return response.json();
})
.then((data) => {
console.log(data);
})
.catch((error) => {
console.error(error.message);
});
await pauses execution until the Promise fulfills — only usable inside async functionsasync function fetchData() {
const response = await fetch(url);
const data = await response.json();
console.log(data);
}
fetch() inside event handlers or effect hooksuseEffect(callback, []) runs the callback once after the component's first render[] as the second argument means the effect only runs once (on mount)import { useEffect, useState } from 'react';
function MyComponent() {
const [data, setData] = useState([]);
useEffect(() => {
fetch(url)
.then(res => res.json())
.then(data => setData(data))
.catch(err => console.error(err));
// optional cleanup function
return () => { /* disconnect listeners */ };
}, []); // empty array = run once on mount
return <div>{JSON.stringify(data)}</div>;
}
.then() and .catch().then() to chain additional .then() callsawait pauses until a Promise resolves[] runs once on mountuseEffect to clean up subscriptions when the component unmounts