Fetch API and JSON Handling
The Fetch API is the modern browser standard for making HTTP network requests to send and receive data from backend servers.
What is it?
The `fetch()` method starts the process of fetching a resource from the network, returning a Promise that resolves to the Response object.
Why is it used?
Used to submit forms via AJAX without page refreshes, load search results dynamically, authenticate users, and fetch course notes from the database.
Detailed Explanation
Fetch Workflows:
1. GET Request: `fetch(url)`
2. POST Request: Pass an options object with `method: 'POST'`, `headers: { 'Content-Type': 'application/json' }`, and `body: JSON.stringify(payload)`.
3. JSON Handling:
• `JSON.stringify(obj)`: Converts JavaScript object into a JSON string to transmit across the network.
• `JSON.parse(str)` or `response.json()`: Converts JSON string received from server back into a JavaScript object.
4. Status Check: Fetch only rejects on network failures, NOT on 404 or 500 errors. You must inspect `response.ok` (status 200-299).
Syntax Structure
Syntax Blueprint
const res = await fetch('/api/endpoint', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ key: 'value' })
});
const data = await res.json();
Code Example
JAVASCRIPT Code
// Marking a Lesson as Completed via Fetch API
async function markLessonCompleted(courseSlug, lessonSlug) {
const payload = {
course_slug: courseSlug,
lesson_slug: lessonSlug,
completed: true
};
try {
const response = await fetch("/api/tutorials/progress", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(payload)
});
const result = await response.json();
if (response.ok && result.success) {
console.log("Lesson progress saved to database! Percentage:", result.completion_percentage + "%");
// Update UI checkbox
document.querySelector(`[data-lesson="${lessonSlug}"] .status-check`)?.classList.add("completed");
} else {
console.warn("Could not save progress:", result.error);
}
} catch (networkError) {
console.error("Network error occurred:", networkError);
}
}
Explanation of the Code
• Sends a JSON POST payload to the Flask backend endpoint `/api/tutorials/progress`.
• Serializes payload using `JSON.stringify()`.
• Checks `response.ok` and parses returned progress data.
Expected Output
Lesson progress is saved in Supabase/SQLite in real-time without reloading the webpage.
Real-World Application
This is the exact implementation used by the IGM Computers student progress tracker.
Common Mistakes to Avoid
• Forgetting `'Content-Type': 'application/json'` in headers, causing backend Flask `request.get_json()` to return None.
• Forgetting `JSON.stringify()` when sending an object in `body`.
Quick Practice Challenge
Write a `fetch` GET call to '/api/search?q=python' and log the returned search results.
Key Takeaways
• Use `fetch()` for all client-server HTTP communication.
• Set `'Content-Type': 'application/json'` and `JSON.stringify()` for POST requests.
• Check `response.ok` to handle HTTP errors.