Computer Science Grade 9 20 min

AJAX Basics

AJAX Basics

Tutorial Preview

1

Introduction & Learning Objectives

Learning Objectives Explain the difference between JSON and XML data formats. Parse a JSON response from a server and display it on a webpage. Differentiate between GET and POST HTTP methods for AJAX requests. Send data to a server using the POST method. Implement basic error handling for failed AJAX requests. Update multiple parts of a webpage using a single AJAX call. Ever wonder how you can like a post or see new comments appear on a social media feed without the whole page reloading? 🤔 That's the power of advanced AJAX! In this lesson, we'll move beyond simple text fetching. You will learn how to work with structured data like JSON, send information back to the server, and handle errors gracefully. These skills are essential for building modern, interactive w...
2

Key Concepts & Vocabulary

TermDefinitionExample JSON (JavaScript Object Notation)A lightweight, text-based format for storing and transporting data. It's easy for humans to read and for computers to parse and generate.`{ "name": "Alex", "grade": 9, "isStudent": true }` XML (eXtensible Markup Language)Another format for structuring data using tags, similar to HTML. It's more verbose than JSON and was more common in older web applications.`<student><name>Alex</name><grade>9</grade></student>` HTTP GET MethodAn HTTP method used to request data from a specified resource. The data is sent in the URL itself.Fetching a user's profile from `/api/users?id=123`. HTTP POST MethodAn HTTP method used to send data to a server to create or...
3

Core Syntax & Patterns

The AJAX Success/Error Pattern if (xhr.readyState === 4 && xhr.status === 200) { /* Success! Use xhr.responseText */ } else if (xhr.readyState === 4) { /* Error! Handle non-200 status */ } Inside the `onreadystatechange` function, always check for both `readyState === 4` (request is done) and `xhr.status === 200` (request was successful). If the status is something else (like 404 or 500), you should handle it as an error. Sending Data with POST xhr.open('POST', '/api/endpoint', true); xhr.setRequestHeader('Content-type', 'application/json'); xhr.send(JSON.stringify(dataObject)); To send data using POST, you must first `open()` the request with 'POST'. Then, use `setRequestHeader()` to tell the server what kind of data...

4 more steps in this tutorial

Sign up free to access the complete tutorial with worked examples and practice.

Sign Up Free to Continue

Sample Practice Questions

Challenging
An API at `/api/dashboard` returns `{"profile": {"name": "Chris"}, "feed": ["Logged in"]}`. Which code block correctly updates both a `<div id="profileName"></div>` and a `<ul id="feedList"></ul>`?
A.let data = JSON.parse(xhr.responseText); document.getElementById('profileName').innerHTML = data.profile.name; document.getElementById('feedList').innerHTML = '<li>' + data.feed[0] + '</li>';
B.let data = xhr.responseText; document.getElementById('profileName').innerHTML = data.profile.name; document.getElementById('feedList').innerHTML = data.feed;
C.You must make two separate AJAX calls to update both elements.
D.let data = JSON.parse(xhr.responseText); document.getElementById('profileName').innerHTML = data.name; document.getElementById('feedList').innerHTML = data.feed[0];
Challenging
A student's error handling logic is: `if (xhr.readyState === 4) { /* success */ } else { /* error */ }`. Why is this incorrect for handling final request states?
A.It correctly identifies errors.
B.It incorrectly assumes any state other than 4 is a final error state, triggering the error block while the request is still loading.
C.It fails to check the `xhr.status` code, so it can't distinguish success from failure.
D.It should use a `try...catch` block instead of `if...else`.
Challenging
To send a `dataObject = {name: 'Jess', email: 'jess@example.com'}` to `/api/register` using POST, what is the correct sequence of `XMLHttpRequest` method calls?
A.xhr.send(dataObject); xhr.open('POST', '/api/register'); xhr.setRequestHeader(...);
B.xhr.open('POST', '/api/register'); xhr.send(JSON.parse(dataObject));
C.xhr.open('POST', '/api/register', true); xhr.setRequestHeader('Content-type', 'application/json'); xhr.send(JSON.stringify(dataObject));
D.xhr.setRequestHeader('Content-type', 'application/json'); xhr.open('POST', '/api/register', true); xhr.send(dataObject);

Want to practice and check your answers?

Sign up to access all questions with instant feedback, explanations, and progress tracking.

Start Practicing Free

More from Advanced Topics

Ready to find your learning gaps?

Take a free diagnostic test and get a personalized learning plan in minutes.