Home > Web Front-end > JS Tutorial > Mastering XMLHttpRequest: A Guide to AJAX Calls in JavaScript

Mastering XMLHttpRequest: A Guide to AJAX Calls in JavaScript

Susan Sarandon
Release: 2024-12-26 08:06:14
Original
932 people have browsed it

Mastering XMLHttpRequest: A Guide to AJAX Calls in JavaScript

XMLHttpRequest for AJAX Calls

The XMLHttpRequest (XHR) object is a core feature of JavaScript that allows you to send and receive data asynchronously from a server without refreshing the web page. It forms the foundation of AJAX (Asynchronous JavaScript and XML), enabling dynamic and interactive web applications.


1. What is XMLHttpRequest?

XMLHttpRequest is an API in JavaScript that facilitates communication with servers through HTTP requests. It supports:

  • Data retrieval without page reloads.
  • Handling various formats like JSON, XML, HTML, and text.
  • Both synchronous and asynchronous operations (though synchronous mode is deprecated for most use cases).

2. Creating an XMLHttpRequest Object

To use XHR, create an instance of the XMLHttpRequest object:

const xhr = new XMLHttpRequest();
Copy after login
Copy after login

3. Steps to Make an XHR Call

  1. Create the XHR Object:
   const xhr = new XMLHttpRequest();
Copy after login
Copy after login
  1. Initialize the Request: Use the open() method to define the HTTP method, URL, and whether the call is asynchronous.
   xhr.open("GET", "https://api.example.com/data", true);
Copy after login
  1. Set Up a Callback for the Response: Use the onreadystatechange event or the load event.
   xhr.onload = function () {
       if (xhr.status === 200) {
           console.log("Response:", xhr.responseText);
       } else {
           console.error("Error:", xhr.status, xhr.statusText);
       }
   };
Copy after login
  1. Send the Request:
   xhr.send();
Copy after login

4. Complete Example: GET Request

const xhr = new XMLHttpRequest();
xhr.open("GET", "https://jsonplaceholder.typicode.com/posts", true);

xhr.onload = function () {
    if (xhr.status === 200) {
        console.log("Data retrieved:", JSON.parse(xhr.responseText));
    } else {
        console.error("Failed to fetch data. Status:", xhr.status);
    }
};

xhr.onerror = function () {
    console.error("Request failed due to a network error.");
};

xhr.send();
Copy after login

5. Sending Data with POST Requests

XHR allows sending data to the server using POST.

Example:

const xhr = new XMLHttpRequest();
xhr.open("POST", "https://jsonplaceholder.typicode.com/posts", true);
xhr.setRequestHeader("Content-Type", "application/json");

xhr.onload = function () {
    if (xhr.status === 201) {
        console.log("Data saved:", JSON.parse(xhr.responseText));
    } else {
        console.error("Error:", xhr.status);
    }
};

const data = JSON.stringify({
    title: "foo",
    body: "bar",
    userId: 1
});

xhr.send(data);
Copy after login

6. Properties and Methods of XHR

Key Properties:

  • readyState: Represents the state of the request (0 to 4).

    • 0: UNSENT
    • 1: OPENED
    • 2: HEADERS_RECEIVED
    • 3: LOADING
    • 4: DONE
  • status: HTTP status code (e.g., 200 for success, 404 for not found).

  • responseText: The response body as a text string.

  • responseXML: The response body as XML data (if applicable).

Key Methods:

  • open(method, url, async): Initializes the request.
  • send(data): Sends the request to the server.
  • setRequestHeader(header, value): Sets custom headers.
  • abort(): Cancels the request.

7. Handling Response States

You can use the onreadystatechange event to monitor the progress of an XHR request.

Example:

const xhr = new XMLHttpRequest();
Copy after login
Copy after login

8. Advantages of Using XHR

  • Asynchronous Communication: Avoids blocking the main thread.
  • Cross-Browser Support: Works across modern and older browsers.
  • Flexible Data Formats: Supports JSON, XML, HTML, and plain text.

9. Limitations of XHR

  • Verbose Syntax: Requires more code compared to modern APIs like fetch.
  • Callback Hell: Complex requests can lead to deeply nested callbacks.
  • Limited Modern Features: Lacks features like Promises or async/await.

10. Modern Alternatives: Fetch API

While XHR is still widely supported, the Fetch API offers a modern, promise-based approach to making HTTP requests.

Fetch Example:

   const xhr = new XMLHttpRequest();
Copy after login
Copy after login

11. Conclusion

XMLHttpRequest is a reliable and well-supported tool for making AJAX calls, but modern APIs like fetch or libraries such as Axios are generally preferred for their simplicity and enhanced features. However, understanding XHR is essential for maintaining legacy code and gaining a deeper knowledge of how asynchronous communication works in JavaScript.

Hi, I'm Abhay Singh Kathayat!
I am a full-stack developer with expertise in both front-end and back-end technologies. I work with a variety of programming languages and frameworks to build efficient, scalable, and user-friendly applications.
Feel free to reach out to me at my business email: kaashshorts28@gmail.com.

The above is the detailed content of Mastering XMLHttpRequest: A Guide to AJAX Calls in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template