Daily theme and context
Day 6 made the Tracker page show data from an array. Today the page starts taking data in and loading it from elsewhere: a registration form that checks what people type, and a learner list loaded from a separate data file with fetch, the same way a real app loads data from a server. You'll also design what the user sees while data is loading, when there is none, and when something fails. Most beginner apps only handle the happy path; professional ones handle all four states.
Your P1 work continues in the Flex hour: a real conversation with someone who has the problem you chose yesterday.
This is Week 2 of the Pilot Cohort's six-week Learn phase ("Frontend"), Day 7 of 30 learning days. Day 7 starts at the Tuesday (24 Nov) 9 pm class; its work goes into Quest 2, due by Sunday 29 Nov, 11:59 pm WAT. It has four blocks, about 6 hours, done whenever suits you except the stand-up: Learn (2 hours, covered in full below), Build (2 hours, section 10: the Learner Project Tracker), Flex (1 hour: your three journals first, then the P1 discovery conversation in section 11), and the live stand-up at 9 pm WAT (1 hour).
Learning objectives
By the end of today, the learner should be able to:
- Listen for an event (a click, a form submit) and respond to it, including stopping a form's default page reload.
- Validate form input in the browser, show your own clear message next to each field, and explain why server-side checks are still needed later.
- Explain what JSON is and convert between JSON text and JavaScript objects.
- Load data with
fetchusingasyncandawait, and handle a failed request withtryandcatch. - Show four states for any data on screen: loading, empty, success and error.
- Run a discovery conversation about a P1 problem and use it to test the four problem questions.
Prerequisite knowledge
Day 6's data-driven Tracker page (data.js and app.js, running through Live Server), and the select-listen-change loop from Day 5.
TechDojo core lesson
Events
An event is something that happens on the page: a click, a key press, a form being submitted. You attach a function that runs when it happens:
const form = document.querySelector("#register-form");
form.addEventListener("submit", (event) => {
event.preventDefault(); // stop the browser reloading the page
// read the inputs, check them, then update the page
});
A form's normal behaviour is to send the data and reload the page. event.preventDefault() stops that, so your JavaScript can handle the data instead.
Why listen for the form's submit rather than a button's click? Submit also fires when someone presses Enter in a field, and assistive technology understands a real form. Put a <button type="submit"> inside the <form> and listen on the form.
Validating input
Validation means checking input before you accept it. There are two layers:
- HTML attributes do simple checks for free:
required,type="email",minlength="2",pattern="[0-9]{11}"(for an 11-digit phone number). - Your own JavaScript handles anything the attributes can't express, and shows a message you write in plain words next to the field, not a vague "Invalid input".
Remember the Chop Express entry task: input values are always text, so trim spaces (value.trim()) and convert numbers (Number(value)) before checking them.
requiredtype="email"minlength="2"pattern="[0-9]{11}"
- Trim and convert values first
- One message next to each field
- Clear the message once it's fixed
Showing your own messages
There's a catch. If a field has required or pattern, the browser checks it first and shows its own small pop-up, and your submit code never runs. To show your own messages, add novalidate to the form. The attributes still describe the rules, and your JavaScript now checks every time:
<form id="register-form" novalidate>
<label for="name">Full name</label>
<input id="name" required aria-describedby="name-error">
<p id="name-error" class="field-error"></p>
<!-- phone and cohort fields, the same way -->
<button type="submit">Register</button>
</form>
form.addEventListener("submit", (event) => {
event.preventDefault();
const name = document.querySelector("#name").value.trim();
const nameError = document.querySelector("#name-error");
nameError.textContent = name === "" ? "Enter the learner's full name." : "";
// check the phone the same way, then add the learner only if every message is empty
});
Each field has its own message element, linked to it with aria-describedby so a screen reader reads the message with the field. Clearing the message when the value is fine matters as much as showing it. For the phone, /^[0-9]{11}$/.test(phone) is true only for exactly 11 digits, such as 08031234567: the same rule as pattern="[0-9]{11}". The /…/ is a regular expression, a pattern for text; this is the only one you need for now.
Validation in the browser is for the user's convenience. It can be bypassed by anyone who knows how, so from Week 3 the same rules must also be enforced where the data is stored. Never treat browser checks as security.
JSON
JSON (JavaScript Object Notation) is the text format apps use to send data. It looks like JavaScript objects and arrays, with every property name in double quotes:
[ { "id": 1, "name": "Ada", "attendance": 9, "sessions": 10 } ]
JSON.parse(text) turns JSON text into JavaScript objects; JSON.stringify(value) turns objects back into text.
JSON is stricter than JavaScript: double quotes only, no comma after the last item, and no comments. One small slip and reading the file fails, which is a good way to test your error state.
Asynchronous code: fetch, async and await
Loading data takes time, from milliseconds to several seconds on a slow connection. JavaScript doesn't stop and wait; it carries on, and the result arrives later. fetch starts a request and returns a promise: a placeholder for a result that isn't there yet. Inside an async function, await pauses that function until the promise settles:
async function loadLearners() {
const response = await fetch("learners.json");
if (!response.ok) throw new Error(`Request failed: ${response.status}`);
return await response.json(); // parse the JSON body into objects
}
Two things go wrong in real apps, so handle both: the request can fail completely (no internet), and the server can answer with an error status such as 404. fetch only throws for the first, which is why the code checks response.ok for the second. Wrap the call in try { … } catch (error) { … } to show an error state instead of crashing.
throw new Error("…") stops the function and reports a problem. try runs the code inside it, and if anything in there throws (a failed request, a 404, broken JSON), it jumps straight to catch instead of crashing the page.
Write the path as fetch("learners.json"), not fetch("/learners.json"). Your GitHub Pages site lives at username.github.io/repository-name/, and a leading slash looks at username.github.io/ instead, so the file is "missing" only online.
- 1
fetch("learners.json")Starts the request and returns a promise - 2
awaitWaits for the response to arrive - 3Check
response.okA 404 doesn't throw on its own - 4
await response.json()Turns the JSON text into objects
The four states
Any data on screen is in one of four states, and the user should always know which:
- Loading: the request is on its way. Show "Loading learners…".
- Empty: it worked, but there's nothing yet. Show "No learners yet. Add the first one." (not a blank page).
- Success: show the data.
- Error: it failed. Say so in plain words and, where it makes sense, offer "Try again".
On slow mobile data, the loading and error states are what many of your users will actually see first. Designing them is part of the job, not decoration.
Here is the shape of the code, using the loadLearners function above:
let learners = []; // filled once the data arrives
const statusText = document.querySelector("#status"); // <p id="status" aria-live="polite">
async function showLearners() {
statusText.textContent = "Loading learners…";
try {
learners = await loadLearners();
if (learners.length === 0) {
statusText.textContent = "No learners yet. Add the first one.";
} else {
statusText.textContent = "";
renderLearners(); // your Day 6 rendering code, moved into a function
}
} catch (error) {
statusText.textContent = "We couldn't load the learners. Check your connection and try again.";
console.error(error);
}
}
showLearners();
aria-live="polite" makes a screen reader announce the status text when it changes. A "Try again" button only needs to call showLearners() again.
- Loading"Loading learners…"
- Empty"No learners yet. Add the first one."
- SuccessThe list itself.
- ErrorPlain words, and a "Try again" button.
Keeping the data in one place
On Day 6 the list came from import. Now it arrives later, so it lives in the learners variable that the whole file can use, and the page is always redrawn from it. Adding a learner from the form is two steps:
learners.push({ id: Date.now(), name, phone, cohort, attendance: 0, sessions: 0 });
renderLearners();
Date.now() (the current time in milliseconds) is a quick way to get an id no other learner has. { name, phone, cohort } is short for { name: name, phone: phone, cohort: cohort }. A new learner has no sessions yet, which is why Day 6's zero check matters. Your lookup from Day 6 keeps working, because it searches the same learners array. And when you refresh the page, the new learner is gone: nothing is saved anywhere yet. Saving is Week 3.
Video resource
Watch the Fetch video in full first. Then watch the crash course's part on async/await (and promises just before it, if the block allows); skip the callbacks part.
Guided viewing questions:
- Why does
fetchneed a second step,response.json(), before you have usable data? - What does
awaitdo, and why can it only be used inside anasyncfunction? - Where would you put the code that shows an error message if the request fails?
Reading resource
Read up to and including the section on validating forms using JavaScript.
MDN, "Using the Fetch API"developer.mozilla.orgRead the opening sections, up to and including checking response status and reading the response body.
Guided reading questions:
- MDN warns that client-side validation is not a security measure. In your own words, why not?
- Name two HTML validation attributes and what each one checks.
- According to MDN, does
fetchreject its promise when the server returns a 404? What do you check instead?
Interactive exercise
In a practice file, running through Live Server:
- 15 min Build a small form with name and phone fields,
requiredon both andnovalidateon the form. On submit, stop the reload, trim the values, and show a message next to each field that fails: name missing; phone not 11 digits. Clear each message once its field is fixed, and show "Saved" when both pass. - 15 min Create
practice.jsonwith three objects. Write anasyncfunction that fetches it and logs the result. Then change the file name in your code to one that doesn't exist and make the page show a clear error message instead of crashing. Put the right name back, add a comma after the last object in the JSON, and check that the same error message appears. - 10 min Add the loading state: show "Loading…" before the request and replace it when the data arrives. Use DevTools → Network → Throttling → "Slow 4G" to slow the request down so you can actually see it.
AI-assisted learning prompt
A useful prompt once your fetch code works:
Here is my JavaScript that loads data with fetch: [paste it]. Don't rewrite it. List every way this could fail for a real user on a slow or unreliable mobile connection, and for each, tell me whether my code already handles it. Then ask me which one I'd fix first and why.
Log it in the AI-use journal: what it listed, which ones your code already handled, and what you changed.
Knowledge check
- What does
event.preventDefault()do in a form's submit handler, and what happens without it? - Why is browser validation not enough on its own? What has to happen later, and where?
- Write, from memory, an
asyncfunction that fetcheslearners.json, checksresponse.ok, and returns the parsed data. - Name the four states of data on screen and write the message you would show for each in the Tracker.
- What is a promise, in one or two plain sentences?
- Your name field has
required, but your own "Enter the learner's full name" message never appears. Why, and what fixes it? - You add a learner with the form, then refresh the page. Where did they go, and why?
Build block: Learner Project Tracker
- Move the data to JSON: turn your Day 6
learnersarray intolearners.jsonand load it withfetchin anasyncfunction, instead of importing it fromdata.js. - Show all four states for the learner list: loading, empty (test it with an empty array in the file), success and error (test it with a wrong file name), with a "Try again" button on the error.
- Add a learner registration form: name, phone and cohort, each with a label, with
requiredand pattern checks,novalidate, and your own JavaScript messages. On a valid submit, add the learner to thelearnersarray, redraw the list (it won't be saved permanently yet; that's Week 3) and clear the form. - Check it on a narrow screen (DevTools device toolbar) so the form is usable on a phone.
- Commit on a branch, merge into
mainthrough a pull request, and check the GitHub Pages link.
Flex hour: your three journals, then the P1 discovery conversation
Do your three journals first (about 20 minutes). Then hold one discovery conversation (about 15 minutes, plus a few minutes for notes) with someone who has the P1 problem you marked yesterday. If you can't reach anyone tonight, book it for tomorrow and use this time to catch up on the Build work; you need the conversation before Thursday's scope draft (Day 9).
Use the Day 1 method exactly:
- Ask about their past behaviour, not their opinion of an idea: "Walk me through the last time this happened."
- Don't mention an app or pitch a solution. The moment you pitch, it stops being discovery.
- Write down at least one direct quote in their own words.
Use the conversation to check your answers to the four problem questions from Day 6, with evidence:
- What do they keep track of, and how? How often do things get lost or forgotten?
- Who else is involved, and what should each person see or change, or not?
- Where are they when the problem bites: at a desk, at a counter, on the road, at home?
- Which part needs judgement or communication: writing to people, summarising, deciding?
If an answer turns out to be "no", that is a useful finding, not a failure. You can choose another problem from your Day 6 list. If no one with the problem is available, a peer can role-play it, but mark your notes clearly as simulated.
Remove names and phone numbers from your notes before pasting them into any AI tool.
Deliverables and submission criteria
Nothing is submitted today. Today, build section B (Forms and loading data) of your Tracker Frontend Pack and add to your P1 scope document. You hand both in for Quest 2 by Sunday 29 Nov, 11:59 pm WAT. Today's work should contain:
0 of 7 ticked Ticks are saved on this device only.
Daily journal reflection
Add today's entry to your three running journals (they're section E of your Frontend Pack):
- Engineering journal: Which of the four states was hardest to make work, and why. Estimate vs actual: for today's Tracker milestone, record your estimate, the actual time, and the reason for any big gap.
- AI-use journal: The failure-modes prompt: what it listed, what you already handled, what you changed.
- Curriculum journal: Did asynchronous code make sense by the end of the day, or does it need more time? Did the discovery conversation confirm your four answers, change them, or make you switch problems?