AJAX stands for Asynchronous JavaScript and XML. It is a method for updating parts of a web page without reloading the entire page. This makes web applications faster, smoother, and more interactive.
AJAX combines:
- HTML and CSS (for content and style)
- JavaScript (for interactivity)
XMLHttpRequest
orFetch API
(to send/receive data)- A server (that provides the data, usually in JSON)
Though “XML” is in the name, AJAX today typically uses JSON instead of XML due to its simplicity.
What is XMLHttpRequest
?
XMLHttpRequest
(XHR) is a built-in JavaScript object used to interact with servers. It allows sending HTTP requests from the browser and handling the response without page reload.
XHR can be used for:
- Fetching data from APIs
- Submitting form data in the background
- Building features like live search, auto-save, etc.
Basic Structure of an AJAX Request with XMLHttpRequest
javascriptCopyEditconst xhr = new XMLHttpRequest();
xhr.open('GET', 'https://jsonplaceholder.typicode.com/posts/1', true);
xhr.onload = function () {
if (xhr.status === 200) {
const data = JSON.parse(xhr.responseText);
console.log(data);
document.getElementById('output').innerText = data.title;
}
};
xhr.onerror = function () {
console.error('Request failed');
};
xhr.send();
Explanation:
new XMLHttpRequest()
creates an XHR object.open(method, URL, async)
prepares the request.onload
runs when the response is received.send()
sends the request.responseText
contains the raw response (usually JSON).status
checks the HTTP response code.
AJAX GET Request Example
Let’s say you want to fetch a post from an API and display it on the page.
htmlCopyEdit<button onclick="loadPost()">Load Post</button>
<div id="output"></div>
<script>
function loadPost() {
const xhr = new XMLHttpRequest();
xhr.open("GET", "https://jsonplaceholder.typicode.com/posts/1", true);
xhr.onload = function () {
if (xhr.status === 200) {
const post = JSON.parse(xhr.responseText);
document.getElementById("output").innerHTML = `<h3>${post.title}</h3><p>${post.body}</p>`;
}
};
xhr.send();
}
</script>
Result:
When you click the button, it fetches and displays a blog post without reloading the page.
AJAX POST Request Example
htmlCopyEdit<button onclick="sendData()">Send Data</button>
<script>
function sendData() {
const xhr = new XMLHttpRequest();
xhr.open("POST", "https://jsonplaceholder.typicode.com/posts", true);
xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xhr.onload = function () {
if (xhr.status === 201) {
const response = JSON.parse(xhr.responseText);
console.log("Data posted:", response);
}
};
const data = {
title: "AJAX Tutorial",
body: "Learning XMLHttpRequest is useful!",
userId: 1
};
xhr.send(JSON.stringify(data));
}
</script>
Key Points:
open('POST', ...)
sets the method.setRequestHeader()
sets headers (especially for JSON).send()
sends a stringified JSON object.
Error Handling
javascriptCopyEditxhr.onerror = function () {
console.error("An error occurred during the request.");
};
Always include error handling to make your app more reliable.
Synchronous vs Asynchronous
AJAX requests are usually asynchronous (true
in open()
) to avoid freezing the browser. If you set it to false
, it becomes synchronous — but this is discouraged in modern development.
Pros and Cons of Using XMLHttpRequest
✅ Pros:
- Supported in all browsers.
- Good for learning the basics of AJAX.
- Full control over the request and response.
❌ Cons:
- Verbose and harder to read than
fetch()
. - Doesn’t use Promises (can result in “callback hell”).
- More boilerplate code.
When to Use XHR
While modern apps use the Fetch API
, learning XHR helps you understand how AJAX works under the hood. It’s also useful for legacy projects or for supporting very old browsers.
Conclusion
XMLHttpRequest
is a powerful way to perform AJAX in JavaScript. It lets you request and send data without reloading the page, which improves the user experience significantly.
Practice Ideas:
- Load a list of users from an API
- Build a live search feature
- Create a contact form that submits via AJAX
Once you understand XMLHttpRequest
, transitioning to fetch()
or libraries like Axios becomes much easier.