Objective. Students capture form input with JavaScript, perform client-side validation with user-facing error messages, and use the Fetch API with async/await to retrieve and display JSON data from a public REST endpoint.
This lesson, its worked examples and its practice questions has not yet been verified by an industry-certified professional or by a certification or approval body. It is a study draft and may contain errors. Do not use it as instructions for work on a job site or on live equipment. Always follow your instructor, your supervising professional, and current official references and regulations.
VoTechWorks program approval and accreditation are still in progress. Credentials are issued only by the certifying bodies named in each program, after their own exams.
Web applications rely on forms to collect user data and on APIs to exchange it. This lesson covers three tightly linked skills: capturing form input with JavaScript, validating that input on the client side before submission, and using the Fetch API to retrieve live JSON data from a remote server.
A form element groups input controls — text boxes, email fields, checkboxes, and more. When a user clicks a submit button, the browser normally sends a request and reloads the page. To validate and handle input without a reload, attach an event listener to the form's `submit` event and call `event.preventDefault()` immediately inside the handler. This stops the default navigation and hands control to your script.
Read each field's current value through `document.getElementById('fieldId').value.trim()`. Trimming removes accidental leading or trailing spaces before you test the value.
Validation checks that user input meets your requirements before it travels anywhere. Common checks include:
Display error messages next to the offending field, not in a browser alert. A typical pattern is to place an empty `<span>` with a unique `id` beside each input and write to its `textContent` when validation fails. Clear all spans at the top of the handler before re-running checks so stale messages do not persist.
Return from the handler without submitting if any check fails. Only proceed — for example, by calling `fetch()` — when every field is valid.
`fetch()` is a built-in browser function that sends HTTP requests and returns a Promise. A Promise represents a value that will be available later. The `async/await` syntax lets you write asynchronous code that reads like synchronous code.
Declare a function with the `async` keyword. Inside it, use `await` before `fetch()` to pause execution until the response arrives, then `await response.json()` to parse the body:
```javascript
async function loadData() {
const statusEl = document.getElementById('status');
statusEl.textContent = 'Loading...';
try {
const response = await fetch('https://jsonplaceholder.typicode.com/users');
if (!response.ok) {
throw new Error(`HTTP error: ${response.status}`);
}
const users = await response.json();
statusEl.textContent = '';
renderCards(users);
} catch (error) {
statusEl.textContent = 'Failed to load data. Check your connection.';
console.error(error);
}
}
```
The `try/catch` block is mandatory. Network failures, DNS errors, and server errors do not automatically surface to the user — your `catch` block must display a readable message.
A loading state — text or a spinner shown before the data arrives — prevents a blank screen and reassures the user that work is in progress. Set it before `fetch()` and clear it after rendering.
After parsing JSON into a JavaScript array, iterate with `forEach` or `map` and build DOM nodes:
```javascript
function renderCards(users) {
const container = document.getElementById('card-container');
container.innerHTML = '';
users.forEach(user => {
const card = document.createElement('div');
card.className = 'card';
card.textContent = user.name;
container.appendChild(card);
});
}
```
Avoid setting `innerHTML` with raw server or API strings directly — that is an XSS risk covered below.
Client-side validation improves user experience — it gives fast feedback. It does not provide security. A malicious user can open browser DevTools, disable your JavaScript, and submit raw HTTP requests directly to your server, bypassing every check you wrote.
Cross-Site Scripting (XSS) is an attack where an adversary injects script tags or event-handler attributes into input fields. If your server stores that input and later renders it as raw HTML, the script runs in every subsequent visitor's browser. The defense is server-side output encoding and input sanitization — always, without exception.
Never concatenate unvalidated user input into `innerHTML`. Use `textContent` for plain text, or a trusted sanitization library when HTML is genuinely needed.
Key rule: validate on the client for UX, validate on the server for security. Both layers must exist independently.
Open DevTools (F12), select the Network tab, and trigger your `fetch()` call. You will see the request, its status code, response headers, and the raw JSON body. This is the primary tool for debugging API calls — check it before assuming your JavaScript is wrong.
Answer each question, then check it. Nothing is recorded; this is your own practice.
A free tech program — complimentary, as our commitment to get America working. Help us build VoTechWorks. Tell us what works, what doesn’t, and what you want to learn.