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
statusin XHR orokin Fetch - Avoid synchronous requests β They block UI and slow performance
- Cross-domain requests β Must handle CORS or same-origin policy
