Lesson 17: AJAX and Fetch API - Revolutionizing Web Interactions
Prefer to listen to this lesson? Click below.
Welcome to an in-depth exploration of AJAX and the Fetch API, two pivotal technologies that have transformed how web applications communicate with servers. In this lesson, we’ll delve into these concepts, providing practical examples and a real-world project related to 24/7 Teach, an online education platform.
Understanding AJAX
AJAX, which stands for Asynchronous JavaScript and XML, is a technique for creating fast and dynamic web pages. It allows web pages to update asynchronously by exchanging data with a web server behind the scenes. This means it's possible to update parts of a web page, without reloading the whole page.
How Does AJAX Work?
An event occurs in a web page (e.g., the page is loaded, a button is clicked)
An XMLHttpRequest object is created by JavaScript
The XMLHttpRequest object sends a request to a web server
The server processes the request
It sends a response back to the web page
The response is read by JavaScript
Proper action (like page update) is performed by JavaScript
AJAX with 24/7 Teach
Imagine you're using 24/7 Teach to browse through different courses. With AJAX, when you click on a course category, the course list can update dynamically without the need for a page refresh. This enhances user experience by providing quick and seamless interactions.
Introducing the Fetch API
The Fetch API provides a more powerful and flexible approach to asynchronous requests. It is a modern alternative to XMLHttpRequest
and uses Promises, making it easier to work with and understand.
Basic Syntax of Fetch API
javascript
fetch(url) .then(response => response.json()) .then(data => console.log(data)) .catch(error => console.error('Error:', error));
Fetch API vs. XMLHttpRequest
Modern and Cleaner Syntax: Fetch uses Promises, making it more readable and organized.
Better Error Handling: Fetch distinguishes between network errors and server responses.
No Need for External Libraries: Fetch is built into the browser.
Using Fetch in 24/7 Teach
For a feature like fetching the details of a selected course, the Fetch API can be used. When a user selects a course, Fetch can request the course details from the server and dynamically display them without a page reload.
Practical Example: Fetching Data
Let's create a simple example to fetch and display a list of courses from 24/7 Teach.
HTML Setup
html
<div id="course-list"></div>
JavaScript Using Fetch API
javascript
fetch('https://api.247teach.org/courses') .then(response => response.json()) .then(courses => { const courseList = document.getElementById('course-list'); courses.forEach(course => { const courseElement = document.createElement('div'); courseElement.innerText = `Course Name: ${course.name}`; courseList.appendChild(courseElement); }); }) .catch(error => console.error('Error:', error));
In this example, we fetch a list of courses from 24/7 Teach’s API. For each course, we create a new div element, set its text, and append it to our course list container.
Error Handling in Fetch
A critical aspect of using Fetch is error handling. Unlike XMLHttpRequest
, Fetch does not reject on HTTP error status. Instead, it resolves normally (with ok
status set to false
), and it only rejects on network failure or if anything prevented the request from completing.
javascript
fetch(url) .then(response => { if (!response.ok) { throw new Error('Network response was not ok'); } return response.json(); }) .then(data => console.log(data)) .catch(error => console.error('Error:', error));
This snippet demonstrates how to check for a successful response and how to handle exceptions properly.
Project Example: Interactive Course Enrollment
Now, let’s apply what we’ve learned to a real-world project. Imagine creating a feature on 24/7 Teach that allows users to enroll in courses interactively.
Project Overview
Objective: Build an interactive course enrollment feature.
Technology: HTML for structure, CSS for styling, and JavaScript with Fetch API for dynamic data handling.
Steps:
User Interface: Create a simple UI with a list of courses and an “Enroll” button next to each course.
Fetch Courses: Use Fetch API to retrieve the list of courses from 24/7 Teach’s API.
Enroll Feature: When a user clicks on “Enroll,” use Fetch to send a POST request to the server, enrolling the user in the course.
Example Code:
HTML:
html
<div id="courses-container"></div>
JavaScript:
javascript
function enrollInCourse(courseId) { fetch(`https://api.247teach.org/enroll/${courseId}`, { method: 'POST' }) .then(response => { if (response.ok) { alert('Enrollment successful!'); } else { alert('Enrollment failed.'); } }) .catch(error => console.error('Error:', error)); } fetch('https://api.247teach.org/courses') .then(response => response.json()) .then(courses => { const coursesContainer = document.getElementById('courses-container'); courses.forEach(course => { const courseElement = document.createElement('div'); courseElement.innerHTML = `Course Name: ${course.name} <button onclick="enrollInCourse(${course.id})">Enroll</button>`; coursesContainer.appendChild(courseElement); }); }) .catch(error => console.error('Error:', error));
In this scenario, each course has an “Enroll” button. When clicked, it triggers enrollInCourse()
, which sends a POST request to enroll the user in the selected course.
Conclusion:
AJAX and the Fetch API are powerful tools in the modern web developer’s arsenal. They allow for the creation of responsive, dynamic, and user-friendly web applications. By integrating these technologies, you can enhance the functionality and interactivity of web applications like 24/7 Teach, improving the overall user experience.
It's time to test our understanding and engage in insightful discussions.
Lesson Questions: Please answer each question in your own words.
Real-World Project: Course Feedback System using Fetch API
Project Overview:
Develop a "Course Feedback System" for 24/7 Teach, where students can submit feedback for the courses they have enrolled in. The system should dynamically fetch course data and post user feedback to the server using Fetch API.
Objective:
To create an interactive system that enhances the user experience by enabling students to submit feedback without reloading the web page.
Technologies:
HTML for structuring the feedback form.
CSS for styling the form and feedback display.
JavaScript with Fetch API for handling asynchronous requests.
Steps:
Feedback Form Setup: Create an HTML form for submitting feedback. Include fields like
courseId
,studentName
,feedback
.Fetching Courses: Use Fetch API to dynamically populate a dropdown with courses available for feedback.
Posting Feedback: When a user submits feedback, use Fetch API to send a POST request to the server with the feedback data.
Update UI: After submission, display a confirmation message without reloading the page.
Example Code
HTML:
html
<form id="feedbackForm"> <select id="courseDropdown"></select> <input type="text" id="studentName" placeholder="Your Name"> <textarea id="feedback" placeholder="Your Feedback"></textarea> <button type="submit">Submit Feedback</button> </form> <div id="confirmationMessage"></div>
JavaScript:
javascript
document.getElementById('feedbackForm').addEventListener('submit', function(e) { e.preventDefault(); const courseId = document.getElementById('courseDropdown').value; const studentName = document.getElementById('studentName').value; const feedback = document.getElementById('feedback').value; fetch('https://api.247teach.org/feedback', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ courseId, studentName, feedback }), }) .then(response => { if (response.ok) { document.getElementById('confirmationMessage').innerText = 'Feedback submitted successfully!'; } else { document.getElementById('confirmationMessage').innerText = 'Failed to submit feedback.'; } }) .catch(error => console.error('Error:', error)); });
Project Execution:
This system enhances the user experience by providing real-time interactions and showcases the practical use of AJAX and Fetch API in handling forms and server communications in a modern web application.
Additional Project Resources:
Article 1: Using the Fetch API
Article 2: AJAX is Being Replaced
Submission Instructions:
Complete the Course Feedback application and integrate it into your existing 24/7 Teach project. Ensure the application is thoroughly tested and debugged.
Submit your project presentation above by EOD, 8 pm Wednesday. You'll receive feedback from your mentor to continuously improve your coding skills.
Evaluation Criteria:
Correct Implementation (40%)
Successfully creates and configures an
XMLHttpRequest
object.Appropriately sets up the request using the
open
method with correct parameters (method, URL, asynchronous flag).
Response Handling (30%)
Efficiently handles server responses in the
onreadystatechange
event handler.Correctly checks for
readyState
andstatus
to ensure successful response processing.Implements meaningful processing or display of the server's response.
Error Handling (15%)
Implements robust error handling, including network errors (using
onerror
) and HTTP error statuses.
Code Quality and Best Practices (10%)
The code is well-organized, readable, and follows JavaScript best practices.
Proper use of comments and naming conventions.
Functionality and Testing (5%)
The AJAX request successfully retrieves and displays data, demonstrating full functionality.
Evidence of thorough testing, ensuring reliability across various scenarios.
Participate in the Group Discussion:
Please answer the discussion question in the comment section below.
How do asynchronous operations like AJAX and Fetch contribute to the user experience in web applications? Discuss scenarios where asynchronous data fetching is essential and how it improves the performance and interactivity of web applications.