AJAX Introduction
Create dynamic web pages without reloading
⚡ What is AJAX?
AJAX (Asynchronous JavaScript and XML) lets you update parts of a web page without reloading the entire page. It sends and receives data from servers in the background.
// Simple AJAX example
function loadContent() {
var xhr = new XMLHttpRequest();
xhr.open("GET", "data.txt", true);
xhr.onload = function() {
document.getElementById("result").innerHTML = xhr.responseText;
};
xhr.send();
}
Output:
Content loaded without page refresh!
Key AJAX Concepts
AJAX combines several web technologies to create seamless user experiences. It uses JavaScript to communicate with servers asynchronously, allowing data exchange without interrupting what users are doing on the page.
Asynchronous
Non-blocking data requests
xhr.open("GET", "url", true);
// true = async
XMLHttpRequest
Core object for AJAX requests
var xhr =
new XMLHttpRequest();
Callbacks
Handle server responses
xhr.onload = function() {
console.log(xhr.responseText);
};
Dynamic Updates
Update page without reload
element.innerHTML =
xhr.responseText;
🔹 How AJAX Works
AJAX follows a simple request-response cycle:
AJAX Workflow:
- User triggers an event (click, type, etc.)
- JavaScript creates XMLHttpRequest object
- Request is sent to server
- Server processes request and sends response
- JavaScript receives response
- Page content is updated dynamically
<!-- HTML -->
<button onclick="loadData()">Load Data</button>
<div id="content"></div>
<script>
function loadData() {
// Create request object
var xhr = new XMLHttpRequest();
// Configure request
xhr.open("GET", "info.txt", true);
// Handle response
xhr.onload = function() {
if (xhr.status == 200) {
document.getElementById("content").innerHTML = xhr.responseText;
}
};
// Send request
xhr.send();
}
</script>
Output:
🔹 Basic AJAX Request
Create a simple GET request:
// Create XMLHttpRequest object
var xhr = new XMLHttpRequest();
// Define what happens on successful response
xhr.onload = function() {
console.log("Response received!");
console.log(xhr.responseText);
};
// Define what happens on error
xhr.onerror = function() {
console.log("Request failed!");
};
// Configure request (method, URL, async)
xhr.open("GET", "data.php", true);
// Send request
xhr.send();
console.log("Request sent!");
Console Output:
Response received!
Hello from server!
🔹 AJAX with POST Method
Send data to server using POST:
function sendData() {
var xhr = new XMLHttpRequest();
xhr.open("POST", "process.php", true);
// Set request header for form data
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.onload = function() {
if (xhr.status == 200) {
document.getElementById("response").innerHTML = xhr.responseText;
}
};
// Send data
var data = "name=John&age=25";
xhr.send(data);
}
// Usage
sendData();
Output:
Data received: John, Age: 25
🔹 Handling Response States
Monitor request progress with readyState:
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
console.log("State: " + xhr.readyState);
// 0 = UNSENT, 1 = OPENED, 2 = HEADERS_RECEIVED
// 3 = LOADING, 4 = DONE
if (xhr.readyState == 4 && xhr.status == 200) {
console.log("Success: " + xhr.responseText);
}
};
xhr.open("GET", "test.php", true);
xhr.send();
Console Output:
State: 2
State: 3
State: 4
Success: Response data
🔹 Modern AJAX with Fetch
Use the modern Fetch API for cleaner code:
// Simple GET request
fetch("data.php")
.then(response => response.text())
.then(data => {
console.log(data);
document.getElementById("output").innerHTML = data;
})
.catch(error => {
console.error("Error:", error);
});
// POST request with JSON
fetch("api.php", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({name: "John", age: 25})
})
.then(response => response.json())
.then(data => console.log(data));
Output:
Data fetched successfully!