← Back to Week 9

AJAX

March 2, 2026 — Slides: AJAX

Topics Covered

HTTP Requests

<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

AJAX

XML vs JSON

fetch()

fetch(url); // sends request, returns a Promise
// next line runs immediately (doesn't wait)

Promises

fetch(url)
    .then((response) => {
        return response.json();
    })
    .then((data) => {
        console.log(data);
    })
    .catch((error) => {
        console.error(error.message);
    });

async/await

async function fetchData() {
    const response = await fetch(url);
    const data = await response.json();
    console.log(data);
}

fetch() in React

useEffect Hook

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>;
}

Key Concepts

Resources