Ajax Request in JavaScript
? AJAX Request in JavaScript
An AJAX request is a way to send data to a server and receive a response without reloading the webpage. JavaScript provides two main ways to make AJAX requests:
? 1. Using XMLHttpRequest (Old Method)
? GET Request Example
function getData() { const xhr = new XMLHttpRequest(); xhr.open("GET", "data.txt", true); // Request to server file xhr.onload = function () { if (xhr.status === 200) { document.getElementById("output").innerHTML = xhr.responseText; } }; xhr.send(); // Send the request}HTML:
<button onclick="getData()">Load Data</button><div id="output"></div>? POST Request Example
function postData() { const xhr = new XMLHttpRequest(); xhr.open("POST", "process.php", true); xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); xhr.onload = function () { if (xhr.status === 200) { console.log(xhr.responseText); } }; xhr.send("name=John&age=30");}? 2. Using fetch() (Modern Method)
? GET Request
function getData() { fetch("data.txt") .then(response => response.text()) .then(data => { document.getElementById("output").innerHTML = data; });}? POST Request
function postData() { fetch("process.php", { method: "POST", headers: { "Content-Type": "application/x-www-form-urlencoded" }, body: "username=JohnDoe" }) .then(response => response.text()) .then(data => { console.log(data); });}? Request Types in AJAX
| Type | Purpose | Example Use |
|---|---|---|
| GET | Get data | Load list, display message |
| POST | Send data | Submit form, save user input |
| PUT | Update data | Update user record |
| DELETE | Remove data | Delete a row or item |
?? AJAX Request Tips
Use
GETfor simple reads andPOSTfor form submissions.Always handle errors using
.catch()(infetch) oronerror(inXMLHttpRequest).Prefer
fetch()for modern applications — it's cleaner and promise-based.
Would you like an example that connects to a PHP/MySQL database or does live search/autocomplete?