Describe AJAX method with example and syntax.
AJAX Method: Description, Syntax, and Example (Web Technologies)
AJAX (Asynchronous JavaScript and XML) is a technique used to send and receive data from a server without reloading the whole web page. Modern apps usually exchange JSON instead of XML. AJAX improves user experience by updating parts of the page dynamically.
How AJAX Works (In Brief)
- User action triggers a JavaScript function (e.g., button click or page load).
- The browser sends an asynchronous HTTP request to the server (GET/POST, etc.).
- The server returns a response (JSON, HTML, text, or XML).
- JavaScript processes the response and updates the DOM instantly without a full reload.
Common AJAX Syntax Options
1) Modern JavaScript: fetch()
// GET request with fetch (JSON)
fetch('/api/products?limit=5', {
method: 'GET',
headers: { 'Accept': 'application/json' }
})
.then(response => {
if (!response.ok) throw new Error('Network error: ' + response.status);
return response.json();
})
.then(data => {
// Update UI using the data
document.getElementById('result').textContent = JSON.stringify(data);
})
.catch(err => {
console.error(err);
document.getElementById('result').textContent = 'Failed to load data.';
});
// POST request with fetch (send JSON)
fetch('/api/feedback', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
},
body: JSON.stringify({ message: 'Great course!', rating: 5 })
});
2) Classic JavaScript: XMLHttpRequest
// POST request with XMLHttpRequest
const xhr = new XMLHttpRequest();
xhr.open('POST', '/api/register', true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) { // request finished
if (xhr.status >= 200 && xhr.status < 300) {
const res = JSON.parse(xhr.responseText);
document.getElementById('result').textContent = 'User ID: ' + res.id;
} else {
document.getElementById('result').textContent = 'Error: ' + xhr.status;
}
}
};
xhr.send(JSON.stringify({ name: 'Aisha', email: 'aisha@example.com' }));
3) jQuery AJAX: $.ajax()
If you use jQuery, the $.ajax() method provides a concise way to make AJAX calls.
// jQuery GET with query params
$.ajax({
url: '/api/users',
type: 'GET', // or 'POST'
dataType: 'json', // expected response format
data: { page: 1, limit: 10 }, // query parameters
timeout: 8000, // optional timeout (ms)
success: function (data, textStatus, jqXHR) {
$('#result').text(JSON.stringify(data));
},
error: function (jqXHR, textStatus, errorThrown) {
$('#result').text('Request failed: ' + textStatus);
}
});
Complete AJAX Example (Load JSON Without Page Reload)
The following example fetches a local JSON file and displays it when the button is clicked.
index.html (core parts)
<div>
<h3>Student List (Loaded via AJAX)</h3>
<button id="loadBtn">Load Students</button>
<pre id="output"></pre>
</div>
<script>
document.getElementById('loadBtn').addEventListener('click', function () {
fetch('students.json', { headers: { 'Accept': 'application/json' } })
.then(r => {
if (!r.ok) throw new Error('HTTP ' + r.status);
return r.json();
})
.then(data => {
// Render nicely
const lines = data.students.map((s, i) => (i + 1) + '. ' + s.name + ' - ' + s.branch);
document.getElementById('output').textContent = lines.join('\n');
})
.catch(err => {
document.getElementById('output').textContent = 'Could not load data: ' + err.message;
});
});
</script>
students.json (sample data)
{
"students": [
{ "name": "Rohan", "branch": "CSE" },
{ "name": "Meera", "branch": "ECE" },
{ "name": "Iqra", "branch": "IT" }
]
}
Key Points for Exams
- AJAX enables asynchronous communication with the server to update parts of a web page.
- Common methods: GET (retrieve data) and POST (send data).
- Use JSON for lightweight data exchange; update the DOM in the success handler.
- Main approaches: fetch() (modern), XMLHttpRequest (legacy), and jQuery $.ajax() (library).
- Always handle errors and check response status codes.
