AJAX Request
AJAX (Asynchronous JavaScript and XML) allows web pages to send requests to a server without reloading. This makes web applications faster and more interactive.
In JavaScript, AJAX requests are usually made using either:
- XMLHttpRequest (XHR) – traditional approach
- Fetch API – modern approach
AJAX Request Using XMLHttpRequest (XHR)
Creating an XHR Object
const xhr = new XMLHttpRequest();
- Creates a new request object.
- Supported in all modern browsers.
Sending a Request to the Server
xhr.open("GET", "data.json", true); // true → asynchronous
xhr.onreadystatechange = function() {
if(xhr.readyState === 4 && xhr.status === 200) {
console.log("Server Response:", xhr.responseText);
}
};
xhr.send();
open(method, url, async)
– Initializes the requestmethod
→"GET"
or"POST"
url
→ Server file or endpointasync
→true
(asynchronous) orfalse
(synchronous)
onreadystatechange
– Fired whenever the request state changesreadyState = 4
→ Request completedstatus = 200
→ Server responded successfullysend()
→ Sends the request
GET Request Example
xhr.open("GET", "demo_get.asp", true);
xhr.send();
// To avoid cached results:
xhr.open("GET", "demo_get.asp?t=" + Math.random(), true);
xhr.send();
// Sending data with GET:
xhr.open("GET", "demo_get2.asp?fname=Henry&lname=Ford", true);
xhr.send();
POST Request Example
xhr.open("POST", "submit.php", true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.onreadystatechange = function() {
if(xhr.readyState === 4 && xhr.status === 200) {
console.log("Server Response:", xhr.responseText);
}
};
xhr.send("name=John&age=25");
setRequestHeader()
→ Sets request headers (e.g., content type)- POST sends data securely in the request body
- Use POST for large data, sensitive input, or updating a database
Synchronous Requests (Not Recommended)
xhr.open("GET", "ajax_info.txt", false); // false → synchronous
xhr.send();
document.getElementById("demo").innerHTML = xhr.responseText;
- Blocks the UI until the response is received
- Rarely used in modern development
AJAX Request Using Fetch API (Modern Approach)
GET Request
fetch("data.json")
.then(response => {
if(!response.ok) throw new Error("Network response was not ok");
return response.json();
})
.then(data => console.log(data))
.catch(error => console.error("Fetch error:", error));
POST Request
fetch("submit.php", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ name: "John", age: 25 })
})
.then(res => res.json())
.then(data => console.log("Server Response:", data))
.catch(err => console.error("Error:", err));
About AJAX Requests
- Asynchronous by default – Keeps the UI responsive
- Handles multiple data formats – JSON, XML, HTML, text
- Error handling – Check
status
in XHR orok
in Fetch - Avoid synchronous requests – They block UI and slow performance
- Cross-domain requests – Must handle CORS or same-origin policy