Home >Web Front-end >JS Tutorial >Mastering XMLHttpRequest: A Guide to AJAX Calls in JavaScript
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.
XMLHttpRequest is an API in JavaScript that facilitates communication with servers through HTTP requests. It supports:
To use XHR, create an instance of the XMLHttpRequest object:
const xhr = new XMLHttpRequest();
const xhr = new XMLHttpRequest();
xhr.open("GET", "https://api.example.com/data", true);
xhr.onload = function () { if (xhr.status === 200) { console.log("Response:", xhr.responseText); } else { console.error("Error:", xhr.status, xhr.statusText); } };
xhr.send();
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();
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);
readyState: Represents the state of the request (0 to 4).
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).
You can use the onreadystatechange event to monitor the progress of an XHR request.
Example:
const xhr = new XMLHttpRequest();
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();
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!