Clean β’ Professional
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:
Creating an XHR Object
const xhr = new XMLHttpRequest();
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 request
method β "GET" or "POST"url β Server file or endpointasync β true (asynchronous) or false (synchronous)onreadystatechange β Fired whenever the request state changesreadyState = 4 β Request completedstatus = 200 β Server responded successfullysend() β Sends the requestGET 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)xhr.open("GET", "ajax_info.txt", false); // false β synchronous
xhr.send();
document.getElementById("demo").innerHTML = xhr.responseText;
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));
status in XHR or ok in Fetch