AJAX keeps your web app fast. You do not need to reload the page every time you send or get data and you save bandwidth. That speeds up the experience. You can load new content or submit forms. That doesn’t stop the userās flow.
Table of Content
In this article, you will learn what Ajax is and how it works in web development. Let’s begin.
Understand What AJAX Is
AJAX refers to Asynchronous JavaScript and XML. It lets your web app talk to the server. It doesnāt reload the page. You send and receive data in the background. You only need to update parts of the page without a full refresh.
AJAX uses built-in browser tools like XMLHttpRequest
or the fetch()
function. These tools make HTTP requests from JavaScript.
You send a request to the server. The server processes it and sends back a response. JavaScript catches that response and updates the page.
AJAX runs in the background. That means users stay on the same page while the app loads new data or sends updates.

Here are steps of how Ajax works in web development:
- A user clicks a button or types in a field.
- JavaScript creates a new
XMLHttpRequest
or usesfetch()
. - The request goes to the server with HTTP.
- The server runs backend code and prepares a response.
- The server sends back data. That is often in JSON.
- JavaScript reads the response.
- JavaScript updates the page and it doesn’t reload it.
In the following part, you will learn how to use the basic XMLHttpRequest
object in plain JavaScript.
Use XMLHttpRequest
in Plain JavaScript
You can use XMLHttpRequest
to make AJAX calls in older browsers or if you want full control.
Here is a simple example:
var xhr = new XMLHttpRequest();
xhr.open("GET", "/data.json", true);
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
var data = JSON.parse(xhr.responseText);
console.log(data);
}
};
xhr.send();
This example makes a GET request. It waits for the server response. It parses and logs it when it gets the data.
Here is how it works:
var xhr = new XMLHttpRequest();
This creates a new XMLHttpRequest
object. You use this object to send a request to a server and receive a response. This is what makes AJAX work.
xhr.open("GET", "/data.json", true);
This sets up the request. It does not send it yet.
"GET"
: The request method. This means the browser asks the server to send back data."/data.json"
: The URL the request will go to. It points to a file nameddata.json
.true
: This makes the request asynchronous. The browser will not wait for a response.
xhr.onreadystatechange = function () { ... };
This sets a function to run every time the request’s state changes. The request goes through several states, from start to finish.
if (xhr.readyState === 4 && xhr.status === 200) { ... }
This checks two things inside the function:
xhr.readyState === 4
: This means the request is done. The full response has arrived.xhr.status === 200
: This means the request succeeded. The server returned “OK”.
Both must be true before you try to use the response.
var data = JSON.parse(xhr.responseText);
This reads the server response. The xhr.responseText
contains the raw text from the server.
JSON.parse(...)
converts that text into a JavaScript object or array so you can work with it.
console.log(data);
This shows the parsed data in the browser console. You can open the console and see what the server sent.
xhr.send();
This actually sends the request to the server. The browser now waits for the server’s response.
You can also send data with POST. Let’s go through that next.
Send POST Requests with AJAX
POST requests let you send data to the server. You use them to create new records or submit form input.
Here is an example:
var xhr = new XMLHttpRequest();
xhr.open("POST", "/submit-form", true);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
console.log("Success:", xhr.responseText);
}
};
var data = JSON.stringify({ name: "Alice", age: 25 });
xhr.send(data);
This code sends JSON data to the server. It sets the right header and waits for a success response.
You already understand the basic XMLHttpRequest
structure. In this code, only a few new parts need to be explained. These relate to the POST method, and headers. Also how to send JSON data.
xhr.open("POST", "/submit-form", true);
"POST"
tells the browser to send data to the server."/submit-form"
is the endpoint that will receive the data.true
keeps the request asynchronous.
xhr.setRequestHeader("Content-Type", "application/json");
This tells the server what kind of data you are sending.
"Content-Type"
is a request header."application/json"
means the data in the request body is JSON.
The server might not read the data correctly without this.
var data = JSON.stringify({ name: "Alice", age: 25 });
This creates a JSON text from a JavaScript object:
{ name: "Alice", age: 25 }
JSON.stringify(...)
turns that into a string:'{"name":"Alice","age":25}'
- This is what
xhr.send()
will send to the server.
xhr.send(data);
This sends the JSON string to the server in the body of the POST request.
The server will read the body, decode the JSON, and handle the form data.
You will see a simpler way to do the same thing with the Fetch API in the next part.
Work with the Fetch API
The Fetch API is newer and easier than XMLHttpRequest
. You write less code, and it reads more clearly.
Here is how to fetch data:
fetch("/data.json")
.then(response => response.json())
.then(data => {
console.log(data);
});
You can also send POST data:
fetch("/submit-form", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({ name: "Alice", age: 25 })
})
.then(response => response.json())
.then(data => {
console.log("Success:", data);
});
Here, you wait for the response. Then you parse it and use it.
This code sends a POST request to /submit-form
. It includes a JSON body with name and age and the header tells the server to expect JSON data. The first .then()
converts the response to an object. The second .then()
logs that object to the console.
You will learn how to work with JSON responses from the server in the next part.
Handle JSON Responses from the Server
Most APIs return data in JSON format. JavaScript can handle this easily. You use .json()
to turn the response into a JavaScript object in Fetch:
fetch("/user")
.then(response => response.json())
.then(user => {
console.log("User ID:", user.id);
console.log("Name:", user.name);
});
You do not have to guess the structure. You can treat the JSON as a normal object once parsed.
Let’s see how to update the page with this data.
Update the DOM with AJAX Results
Once you get data from the server, you can show it in the page. You change the DOM with innerHTML
or textContent
.
Here is an example:
fetch("/user")
.then(response => response.json())
.then(user => {
document.getElementById("username").textContent = user.name;
document.getElementById("email").textContent = user.email;
});
You do not reload the page. You just plug the new data into the right spot.
In the next section, you will learn how to show a spinner while waiting for data.
Add a Loading Spinner for AJAX Calls
Users need feedback while they wait. You can show a spinner with the AJAX call.
Here is how:
const spinner = document.getElementById("spinner");
spinner.style.display = "block";
fetch("/user")
.then(response => response.json())
.then(user => {
spinner.style.display = "none";
document.getElementById("username").textContent = user.name;
});
Show the spinner before the request. Hide it after the data comes back. Keep the user in the loop.
Now you will learn how to handle errors if something goes wrong.
Handle Error in AJAX
AJAX calls can fail. The server might return an error. The network might go down. You must check for problems and tell the user.
Use .catch()
and check the response with Fetch:
fetch("/user")
.then(response => {
if (!response.ok) {
throw new Error("Server error");
}
return response.json();
})
.then(data => {
console.log("User:", data);
})
.catch(error => {
console.error("Request failed:", error);
alert("Could not load user info");
});
You do not let failures stay silent. You log them and inform the user. Now Let’s wrap up and go over what you have seen.
Wrapping Up
You learned what AJAX is and how it helps your web app work faster. That does not reload the page. You saw how it keeps the user on the page while loading or sending data in the background.
Also, you saw how to use the XMLHttpRequest
object to send both GET and POST requests. You learned how to set headers and send JSON data. Also, handle responses.
Then you saw how the Fetch API works. It gives you a cleaner way to write the same requests. You learned how to use .json()
to read the response and how to use .catch()
to handle errors.
Here is a quick recap:
- AJAX lets you send and receive data
XMLHttpRequest
gives you full control for older browsers- The Fetch API gives you cleaner, simpler code
- You can send GET or POST requests with JSON data
- You can update the DOM after you get data
- A spinner helps users see that something is loading
- Handle error shows alerts and logs issues
FAQs
What is AJAX and how does it work in web development?
What are the steps of an AJAX request?
- The user clicks something or types in a field
- JavaScript creates a new request using XMLHttpRequest or fetch()
- The request goes to the server
- The server runs backend code and sends a response
- The response comes back, often in JSON
- JavaScript reads it
- JavaScript updates part of the page
How do I use XMLHttpRequest to make an AJAX call?
var xhr = new XMLHttpRequest();
xhr.open("GET", "/data.json", true);
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
var data = JSON.parse(xhr.responseText);
console.log(data);
}
};
xhr.send();
How do I send POST data with AJAX?
What is the Fetch API and how is it better than XMLHttpRequest?
fetch("/data.json")
.then(response => response.json())
.then(data => {
console.log(data);
});
How do I update the page using AJAX results?
document.getElementById("username").textContent = user.name;