You are currently viewing JavaScript Cheat Sheet 11.1.2: AJAX XMLHttpRequest

JavaScript Cheat Sheet 11.1.2: AJAX XMLHttpRequest

The XMLHttpRequest Object: A Comprehensive Guide


AJAX (Asynchronous JavaScript and XML) is a powerful technology that allows web pages to asynchronously send and receive data from a web server without interfering with the display and behavior of the existing page. At the heart of AJAX lies the XMLHttpRequest object, which provides the functionality to make HTTP requests from the client-side.

In this tutorial, we’ll delve into the basics of AJAX, focusing specifically on the XMLHttpRequest object. By the end of this tutorial, you’ll have a solid understanding of how to use XMLHttpRequest to create dynamic and interactive web applications.

Getting Started


Let’s start by understanding the XMLHttpRequest object and its basic usage.

Step 1: Creating an XMLHttpRequest Object


The first step is to create an instance of the XMLHttpRequest object. This can be done using the following JavaScript code:

var xhttp = new XMLHttpRequest();

Explanation:

  • We declare a variable xhttp and assign it a new instance of the XMLHttpRequest object using the new keyword.

Step 2: Making a GET Request


Now, let’s make a simple GET request to fetch data from a server. We’ll use the open() and send() methods of the XMLHttpRequest object.

xhttp.open("GET", "https://jsonplaceholder.typicode.com/posts/1", true);
xhttp.send();

Explanation:

  • The open() method initializes the request. It takes three parameters:
  • The HTTP method (GET, POST, etc.).
  • The URL of the resource to fetch.
  • A boolean indicating whether the request should be asynchronous (true) or not (false).
  • The send() method sends the request to the server.

Step 3: Handling the Response


Once the request is sent, we need to handle the response from the server. We’ll use the onreadystatechange event and the readyState and status properties to determine the status of the request and process the response accordingly.

xhttp.onreadystatechange = function() {
  if (this.readyState == 4 && this.status == 200) {
    console.log(this.responseText);
  }
};

Explanation:

  • The onreadystatechange event is triggered whenever the readyState property of the XMLHttpRequest object changes.
  • Inside the event handler, we check if the readyState is 4 (request is complete) and the status is 200 (OK).
  • If both conditions are met, we log the response text to the console.

Sample Output:
If the request is successful, you should see the response data logged to the console.

{
  "userId": 1,
  "id": 1,
  "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
  "body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
}

Conclusion


In this tutorial, we’ve covered the basics of using the XMLHttpRequest object in AJAX to make asynchronous requests to a server and handle the responses. This is just the tip of the iceberg in terms of what you can achieve with AJAX, but it provides a solid foundation for building dynamic and interactive web applications. Experiment with different HTTP methods, handle errors gracefully, and explore more advanced AJAX techniques to take your web development skills to the next level.

Leave a Reply