AJAX Request
Sending data to servers with AJAX
📤 What is an AJAX Request?
An AJAX request sends data to a server without reloading the page. You can use GET to retrieve data or POST to send data, enabling dynamic interactions with servers.
// Simple GET request
xhr.open('GET', 'data.php', true);
xhr.send();
Request Types
GET Request
Retrieve data from server
xhr.open('GET', 'api/users');
POST Request
Send data to server
xhr.open('POST', 'api/save');
PUT Request
Update existing data
xhr.open('PUT', 'api/update');
DELETE Request
Remove data from server
xhr.open('DELETE', 'api/delete');
🔹 GET Request
GET requests retrieve data from servers. They're simple, fast, and ideal for fetching information without modifying server data.
// Basic GET request
const xhr = new XMLHttpRequest();
xhr.onload = function() {
if (xhr.status === 200) {
console.log(xhr.responseText);
}
};
xhr.open('GET', 'data.txt', true);
xhr.send();
Console Output:
Data retrieved from server successfully!
🔹 GET with Parameters
You can send parameters with GET requests by appending them to the URL. This allows filtering or customizing server responses based on your needs.
// GET request with parameters
const xhr = new XMLHttpRequest();
xhr.onload = function() {
document.getElementById('result').innerHTML = xhr.responseText;
};
// Add parameters to URL
const params = '?id=123&name=John';
xhr.open('GET', 'user.php' + params, true);
xhr.send();
URL Parameters:
- ? - Starts the query string
- & - Separates multiple parameters
- = - Assigns values to parameters
🔹 POST Request
POST requests send data to servers for processing. Unlike GET, POST can handle large amounts of data and is more secure for sensitive information.
// POST request example
const xhr = new XMLHttpRequest();
xhr.onload = function() {
if (xhr.status === 200) {
console.log('Data sent successfully!');
}
};
xhr.open('POST', 'submit.php', true);
// Set content type for POST
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
// Send data in request body
xhr.send('name=John&[email protected]');
Console Output:
Data sent successfully!
🔹 POST with JSON
Modern applications often use JSON format for data exchange. JSON provides a clean, structured way to send complex data to servers.
// POST request with JSON data
const xhr = new XMLHttpRequest();
xhr.onload = function() {
const response = JSON.parse(xhr.responseText);
console.log(response);
};
xhr.open('POST', 'api/users', true);
// Set JSON content type
xhr.setRequestHeader('Content-Type', 'application/json');
// Create JSON data
const data = {
name: 'John Doe',
email: '[email protected]',
age: 30
};
// Send JSON string
xhr.send(JSON.stringify(data));
🔹 Complete Request Example
Here's a practical example showing both GET and POST requests in a form submission scenario:
<!DOCTYPE html>
<html>
<body>
<h2>User Registration</h2>
<input type="text" id="username" placeholder="Username">
<input type="email" id="email" placeholder="Email">
<button onclick="submitForm()">Submit</button>
<div id="message"></div>
<script>
function submitForm() {
const xhr = new XMLHttpRequest();
xhr.onload = function() {
if (xhr.status === 200) {
document.getElementById('message').innerHTML =
'✅ Registration successful!';
}
};
xhr.open('POST', 'register.php', true);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
const username = document.getElementById('username').value;
const email = document.getElementById('email').value;
xhr.send('username=' + username + '&email=' + email);
}
</script>
</body>
</html>