Create AJAX Requests with XMLHttpRequest

HTMLHTMLBeginner
Practice Now

Introduction

In this lab, participants will explore the powerful world of AJAX (Asynchronous JavaScript and XML) and learn how to create dynamic web applications using XMLHttpRequest. The comprehensive tutorial covers the fundamental concepts of asynchronous web communication, guiding learners through the process of sending and receiving data from servers without page reloads.

Participants will gain practical skills in creating XMLHttpRequest objects, configuring HTTP request methods, handling server response states, and implementing basic AJAX data retrieval techniques. By understanding these core principles, developers will be equipped to build more responsive and interactive web experiences that enhance user engagement and application performance.

Understand AJAX and Asynchronous Requests

In this step, you'll learn about AJAX (Asynchronous JavaScript and XML) and how it revolutionizes web communication. AJAX allows web pages to update content dynamically without reloading the entire page, creating a smoother and more responsive user experience.

What is AJAX?

AJAX is a web development technique that enables web applications to send and receive data from a server asynchronously (in the background) without interfering with the display and behavior of the existing page. This means you can update parts of a web page without refreshing the entire page.

Key Characteristics of Asynchronous Requests

  1. Non-Blocking: Unlike traditional synchronous requests, AJAX allows the browser to continue executing other tasks while waiting for server response.
  2. Background Communication: Data can be exchanged with the server without interrupting the user's current interaction.
  3. Partial Page Updates: Only specific parts of a web page can be updated, improving performance and user experience.

Simple AJAX Concept Demonstration

Let's create a simple HTML file to illustrate the concept of asynchronous requests. We'll use the WebIDE to create this example.

Open the WebIDE and create a new file ~/project/ajax-demo.html:

<!doctype html>
<html>
  <head>
    <title>AJAX Demonstration</title>
  </head>
  <body>
    <h1>AJAX Example</h1>
    <button id="loadData">Load Data</button>
    <div id="result"></div>

    <script>
      document
        .getElementById("loadData")
        .addEventListener("click", function () {
          console.log("Button clicked: Initiating AJAX request");
          // Asynchronous request will be implemented in later steps
        });
    </script>
  </body>
</html>

Real-World AJAX Use Cases

  • Autocomplete search suggestions
  • Live content updates
  • Form submissions without page reload
  • Polling for new notifications
  • Fetching data from APIs

Why Asynchronous Requests Matter

Asynchronous requests solve several web development challenges:

  • Improved user experience
  • Reduced server load
  • Faster, more responsive web applications
  • More efficient data exchange

Create XMLHttpRequest Object

In this step, you'll learn how to create an XMLHttpRequest object, which is the core mechanism for making asynchronous requests in JavaScript. We'll build upon the previous step's HTML file and add the XMLHttpRequest functionality.

Open the ~/project/ajax-demo.html file in the WebIDE and update the script section to create an XMLHttpRequest object:

<!doctype html>
<html>
  <head>
    <title>XMLHttpRequest Demonstration</title>
  </head>
  <body>
    <h1>AJAX Request Example</h1>
    <button id="loadData">Load Data</button>
    <div id="result"></div>

    <script>
      document
        .getElementById("loadData")
        .addEventListener("click", function () {
          // Create XMLHttpRequest object
          var xhr = new XMLHttpRequest();

          // Log the creation of XMLHttpRequest object
          console.log("XMLHttpRequest object created:", xhr);
        });
    </script>
  </body>
</html>

Understanding XMLHttpRequest Object

The XMLHttpRequest (XHR) object is a built-in browser API that allows you to:

  • Create HTTP requests
  • Send data to a server
  • Receive data from a server
  • Update parts of a web page without reloading

Key Methods of XMLHttpRequest

  1. open(): Initializes a new request
  2. send(): Sends the request to the server
  3. onreadystatechange: Tracks the state of the request

Browser Compatibility

XMLHttpRequest is supported in all modern browsers, making it a reliable choice for AJAX communications. Modern web development also uses the Fetch API, but XMLHttpRequest remains widely used.

Example Output

When you click the "Load Data" button, you'll see a console log demonstrating the creation of the XMLHttpRequest object:

XMLHttpRequest object created: XMLHttpRequest {...}

Configure HTTP Request Methods

In this step, you'll learn how to configure HTTP request methods using XMLHttpRequest. We'll update the ajax-demo.html file to demonstrate how to set up different types of HTTP requests.

Open the ~/project/ajax-demo.html file in the WebIDE and modify the script section:

<!doctype html>
<html>
  <head>
    <title>HTTP Request Methods</title>
  </head>
  <body>
    <h1>AJAX Request Methods</h1>
    <button id="getButton">GET Request</button>
    <button id="postButton">POST Request</button>
    <div id="result"></div>

    <script>
      // GET Request Configuration
      document
        .getElementById("getButton")
        .addEventListener("click", function () {
          var xhr = new XMLHttpRequest();

          // Configure GET request
          xhr.open("GET", "https://jsonplaceholder.typicode.com/posts/1", true);

          // Set request headers
          xhr.setRequestHeader("Content-Type", "application/json");

          // Log request details
          console.log("GET Request Configured");

          // Send the request
          xhr.send();
        });

      // POST Request Configuration
      document
        .getElementById("postButton")
        .addEventListener("click", function () {
          var xhr = new XMLHttpRequest();

          // Configure POST request
          xhr.open("POST", "https://jsonplaceholder.typicode.com/posts", true);

          // Set request headers
          xhr.setRequestHeader("Content-Type", "application/json");

          // Prepare data to send
          var data = JSON.stringify({
            title: "foo",
            body: "bar",
            userId: 1
          });

          // Log request details
          console.log("POST Request Configured");

          // Send the request with data
          xhr.send(data);
        });
    </script>
  </body>
</html>

HTTP Request Methods

The most common HTTP request methods are:

  1. GET: Retrieve data from a server
  2. POST: Submit data to be processed by the server
  3. PUT: Update existing data
  4. DELETE: Remove data

Key Methods for Configuring Requests

  • open(method, url, async):

    • method: HTTP method (GET, POST, etc.)
    • url: Server endpoint
    • async: Boolean for asynchronous request (usually true)
  • setRequestHeader(): Set request headers

  • send(): Send the request (with optional data)

Example Output

When you click the buttons, you'll see console logs:

GET Request Configured
POST Request Configured

Handle Server Response States

In this step, you'll learn how to handle different states of an XMLHttpRequest and process server responses. We'll update the ajax-demo.html file to demonstrate response handling.

Open the ~/project/ajax-demo.html file in the WebIDE and modify the script section:

<!doctype html>
<html>
  <head>
    <title>Server Response Handling</title>
  </head>
  <body>
    <h1>AJAX Response States</h1>
    <button id="fetchData">Fetch Data</button>
    <div id="result"></div>

    <script>
      document
        .getElementById("fetchData")
        .addEventListener("click", function () {
          var xhr = new XMLHttpRequest();
          var resultDiv = document.getElementById("result");

          // Track request states
          xhr.onreadystatechange = function () {
            // Log current ready state
            console.log("Ready State:", xhr.readyState);

            // Check if request is complete and successful
            if (xhr.readyState === 4) {
              if (xhr.status === 200) {
                // Successful response
                try {
                  var data = JSON.parse(xhr.responseText);
                  resultDiv.innerHTML = `
                                <h3>Data Received:</h3>
                                <pre>${JSON.stringify(data, null, 2)}</pre>
                            `;
                  console.log("Request Successful");
                } catch (error) {
                  resultDiv.innerHTML = "Error parsing response";
                  console.error("Parsing Error:", error);
                }
              } else {
                // Error handling
                resultDiv.innerHTML = `Error: ${xhr.status}`;
                console.error("Request Failed", xhr.status);
              }
            }
          };

          // Configure and send request
          xhr.open("GET", "https://jsonplaceholder.typicode.com/posts/1", true);
          xhr.send();
        });
    </script>
  </body>
</html>

XMLHttpRequest Ready States

XMLHttpRequest has 5 ready states:

  • 0: UNSENT (request not initialized)
  • 1: OPENED (connection established)
  • 2: HEADERS_RECEIVED (request received)
  • 3: LOADING (processing request)
  • 4: DONE (request complete)

Response Handling Key Concepts

  1. Use onreadystatechange to track request progress
  2. Check readyState === 4 for completed requests
  3. Verify status === 200 for successful responses
  4. Use responseText or responseXML to access data
  5. Implement error handling for different status codes

Example Output

When you click "Fetch Data", you'll see console logs:

Ready State: 1
Ready State: 2
Ready State: 3
Ready State: 4
Request Successful

Implement Basic AJAX Data Retrieval

In this step, you'll learn how to retrieve and display data from an API using AJAX. We'll create a simple user management application that fetches and displays user information.

Open the ~/project/ajax-demo.html file in the WebIDE and replace its contents with the following code:

<!doctype html>
<html>
  <head>
    <title>User Management App</title>
    <style>
      #userList {
        margin-top: 20px;
        border: 1px solid #ddd;
        padding: 10px;
      }
    </style>
  </head>
  <body>
    <h1>User Management</h1>
    <button id="fetchUsers">Fetch Users</button>
    <div id="userList"></div>

    <script>
      document
        .getElementById("fetchUsers")
        .addEventListener("click", function () {
          var xhr = new XMLHttpRequest();
          var userListDiv = document.getElementById("userList");

          xhr.onreadystatechange = function () {
            if (xhr.readyState === 4) {
              if (xhr.status === 200) {
                try {
                  var users = JSON.parse(xhr.responseText);

                  // Clear previous content
                  userListDiv.innerHTML = "<h2>User List</h2>";

                  // Create user list
                  users.forEach(function (user) {
                    var userDiv = document.createElement("div");
                    userDiv.innerHTML = `
                                    <p>
                                        <strong>Name:</strong> ${user.name}<br>
                                        <strong>Email:</strong> ${user.email}<br>
                                        <strong>Company:</strong> ${user.company.name}
                                    </p>
                                `;
                    userListDiv.appendChild(userDiv);
                  });
                } catch (error) {
                  userListDiv.innerHTML = "Error parsing user data";
                }
              } else {
                userListDiv.innerHTML = `Error fetching users: ${xhr.status}`;
              }
            }
          };

          // Fetch users from JSONPlaceholder API
          xhr.open("GET", "https://jsonplaceholder.typicode.com/users", true);
          xhr.send();
        });
    </script>
  </body>
</html>

Key Concepts of Data Retrieval

  1. Use a public API (JSONPlaceholder) for demonstration
  2. Fetch multiple user records
  3. Parse JSON response
  4. Dynamically create HTML elements
  5. Handle potential errors

Example Output

When you click "Fetch Users", you'll see a list of users with their details:

User List
Name: Leanne Graham
Email: [email protected]
Company: Romaguera-Crona

Name: Ervin Howell
Email: [email protected]
Company: Deckow-Crist

... (more users)

Best Practices

  • Always validate and sanitize data
  • Implement error handling
  • Use try-catch for JSON parsing
  • Create dynamic and responsive UI

Summary

In this lab, participants explore the fundamentals of AJAX and asynchronous web communication, learning how to create dynamic web experiences without full page reloads. The lab introduces key concepts such as non-blocking requests, background data exchange, and partial page updates, demonstrating how XMLHttpRequest enables seamless interaction between web clients and servers.

By walking through practical examples and understanding AJAX's core principles, learners gain insights into implementing responsive web applications that can fetch and display data dynamically. The lab covers essential techniques for creating XMLHttpRequest objects, configuring HTTP methods, handling server responses, and retrieving data asynchronously, providing a comprehensive foundation for modern web development practices.