JavaScript

coding learning websites codepractice

JS Basics

JS Variables & Operators

JS Data Types & Conversion

JS Numbers & Math

JS Strings

JS Dates

JS Arrays

JS Control Flow

JS Loops & Iteration

JS Functions

JS Objects

JS Classes & Modules

JS Async Programming

JS Advanced

JS HTML DOM

JS BOM (Browser Object Model)

JS Web APIs

JS AJAX

JS JSON

JS Graphics & Charts

JavaScript AJAX XMLHttp


AJAX stands for Asynchronous JavaScript and XML, and the core of AJAX communication is the XMLHttpRequest object. This object allows JavaScript to send and receive data from a web server without reloading the page.

Although the name contains “XML,” it can work with any data type—HTML, text, or JSON. The XMLHttpRequest object is one of the oldest yet most reliable ways to make AJAX calls in JavaScript.

What Is XMLHttpRequest?

The XMLHttpRequest (XHR) object is built into most browsers and lets your JavaScript code communicate directly with the server in the background.
With it, you can:

  • Send data to the server

  • Receive data from the server

  • Update part of a webpage dynamically

This is the base concept behind most modern JavaScript frameworks like React, Angular, and Vue when they perform API requests.

Creating an XMLHttpRequest Object

You can create an XHR object using the new keyword.

// Create an XMLHttpRequest object
let xhr = new XMLHttpRequest();

This object gives you access to several methods and properties that let you send requests and handle responses.

Steps to Send a Request Using XMLHttpRequest

An AJAX request with XMLHttpRequest usually follows these steps:

  1. Create a new XMLHttpRequest object.

  2. Open the request using the open() method.

  3. Send the request to the server using the send() method.

  4. Handle the server response using the onreadystatechange event.

Example: Loading Data from a Text File

Here’s a simple example that loads data from a file called data.txt and displays it on the page.

<!DOCTYPE html>
<html>
<body>
  <h2>Load Text File using AJAX</h2>
  <button onclick="loadData()">Load Content</button>
  <div id="output"></div>

  <script>
    function loadData() {
      // Create a new XMLHttpRequest object
      let xhr = new XMLHttpRequest();

      // Define what should happen when the response is ready
      xhr.onreadystatechange = function() {
        // readyState 4 means the operation is complete
        // status 200 means "OK" (successful request)
        if (this.readyState == 4 && this.status == 200) {
          document.getElementById("output").innerHTML = this.responseText;
        }
      };

      // Initialize a GET request to the file
      xhr.open("GET", "data.txt", true);

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

Explanation

  • xhr.open("GET", "data.txt", true) sets up the request.

    • "GET" means we are requesting data.

    • "data.txt" is the file we want.

    • true makes it asynchronous (the page doesn’t freeze).

  • xhr.send() sends the request to the server.

  • xhr.onreadystatechange triggers every time the request state changes.

  • When readyState is 4 and status is 200, the response is available.

XMLHttpRequest Ready States

The readyState property shows the current state of the request.

Value State Description
0 UNSENT Request not initialized
1 OPENED Connection established
2 HEADERS_RECEIVED Request received
3 LOADING Processing request
4 DONE Request finished and response ready

Handling Errors in XMLHttpRequest

When something goes wrong (like a 404 or network issue), you can handle it properly using the status code.

if (this.readyState == 4) {
  if (this.status == 200) {
    console.log("Request successful:", this.responseText);
  } else {
    console.error("Error loading file:", this.status);
  }
}

This ensures your application doesn’t silently fail when the request fails.

Using POST Method with XMLHttpRequest

While GET requests fetch data, POST requests send data to the server.

Example: sending user input to a server file server.php.

<!DOCTYPE html>
<html>
<body>
  <h2>Send Data using POST</h2>
  <input type="text" id="username" placeholder="Enter your name">
  <button onclick="sendData()">Send</button>
  <p id="response"></p>

  <script>
    function sendData() {
      // Get input value
      let name = document.getElementById("username").value;
      let xhr = new XMLHttpRequest();

      xhr.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
          document.getElementById("response").innerHTML = this.responseText;
        }
      };

      // Open a POST request
      xhr.open("POST", "server.php", true);

      // Set request header to send form data
      xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

      // Send data
      xhr.send("username=" + encodeURIComponent(name));
    }
  </script>
</body>
</html>

Explanation

  • xhr.open("POST", "server.php", true) prepares a POST request.

  • xhr.setRequestHeader() sets the request type.

  • xhr.send() sends the actual data.

  • The data (username) is sent to the server-side file for processing.

Using JSON with XMLHttpRequest

Most modern applications exchange data in JSON format.

let xhr = new XMLHttpRequest();
xhr.open("GET", "data.json", true);

xhr.onload = function() {
  if (xhr.status === 200) {
    // Parse JSON data
    let data = JSON.parse(xhr.responseText);

    // Display a value from the JSON
    console.log("User Name:", data.name);
  }
};

xhr.send();

Here, JSON.parse() converts the JSON text into a JavaScript object so you can easily use it in your code.

Synchronous vs Asynchronous Requests

  • Asynchronous (Recommended):
    The code continues running while the request is processed.
    This keeps your webpage responsive.

  • Synchronous:
    The page waits for the response, which can cause it to freeze.
    Example:

    xhr.open("GET", "data.txt", false); // false = synchronous
    

Synchronous requests are deprecated in modern browsers because they block the user interface.

Common Properties and Methods of XMLHttpRequest

Method/Property Description
open(method, url, async) Initializes request
send() Sends request to server
setRequestHeader(header, value) Sets HTTP request headers
readyState Holds the current state
status Returns the HTTP status code
responseText Returns response data as text
onreadystatechange Defines a function to call when ready state changes

Summary of the Tutorial

The XMLHttpRequest object is the foundation of AJAX communication. It allows data exchange between the client and server without reloading the page. By using its methods like open(), send(), and properties like readyState and status, you can easily send and receive text, HTML, or JSON data.

Although newer features like Fetch API are now more common, learning XMLHttpRequest is still valuable for understanding how AJAX works at a lower level and for maintaining older codebases.


Practice Questions

  1. Create an XMLHttpRequest to fetch a text file (info.txt) and display its content inside a <div> when a button is clicked.

  2. Write code to check the readyState and status of an XMLHttpRequest and log appropriate messages for loading, success, or failure.

  3. Fetch a JSON file (user.json) using XMLHttpRequest and display the name and email values on the page.

  4. Create a POST request using XMLHttpRequest to send a username and email to submit.php and display the server response.

  5. Modify an XMLHttpRequest to show a “Loading…” message in a <div> before the server responds.

  6. Write code that handles errors for XMLHttpRequest requests, logging 404 or 500 errors to the console.

  7. Create two buttons that each send an XMLHttpRequest to different text files (students.txt and teachers.txt) and display results in the same <div>.

  8. Use XMLHttpRequest to fetch an HTML snippet (snippet.html) and insert it into a specific section of the page without refreshing.

  9. Write code that parses an array of JSON objects from a file and dynamically creates a list of user names and ages in the DOM.

  10. Implement a synchronous XMLHttpRequest (for learning only) and observe how it blocks page interaction until the response is received.


JavaScript

online coding class codepractice

JS Basics

JS Variables & Operators

JS Data Types & Conversion

JS Numbers & Math

JS Strings

JS Dates

JS Arrays

JS Control Flow

JS Loops & Iteration

JS Functions

JS Objects

JS Classes & Modules

JS Async Programming

JS Advanced

JS HTML DOM

JS BOM (Browser Object Model)

JS Web APIs

JS AJAX

JS JSON

JS Graphics & Charts

Go Back Top