Clean β’ Professional
AJAX is a web development technique that allows web pages to communicate with a server asynchronously without reloading the entire page. This makes web applications faster, smoother, and more interactive.
Despite the name, AJAX is not limited to XML; it often uses JSON, plain text, or HTML as the data format.
const xhr = new XMLHttpRequest();
xhr.open("GET", "<https://api.example.com/data>", true);
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
console.log("Response:", xhr.responseText);
}
};
xhr.send();
open() β Sets up the request (method, URL, async flag)onreadystatechange β Event triggered when request state changesreadyState === 4 β Request completedstatus === 200 β Request successfulsend() β Sends the request to the serverThe Fetch API is simpler and Promise-based.
fetch("<https://api.example.com/data>")
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error("Error:", error));
<button id="loadBtn">Load Data</button>
<div id="result"></div>
<script>
document.getElementById("loadBtn").addEventListener("click", () => {
fetch("https://jsonplaceholder.typicode.com/posts/1")
.then(response => response.json())
.then(data => {
document.getElementById("result").innerHTML = `<h3>${data.title}</h3><p>${data.body}</p>`;
});
});
</script>Β