AJAX Request

Sending requests to the server

📤 What is an AJAX Request?

An AJAX request is like sending a letter to the server asking for information or telling it to do something. You can ask for data (GET) or send data (POST)!


// Basic AJAX request structure
const xhr = new XMLHttpRequest();
xhr.open('GET', 'api/users.json', true);  // What, Where, Async
xhr.send();  // Send the request!

// The request is now flying to the server! ✈️
                                    

Request Journey:

1. 📝 Create request

2. 🎯 Set destination

3. 🚀 Send to server

4. ⏳ Wait for response

Types of AJAX Requests

📥

GET Request

Ask server for data

xhr.open('GET', 'data.json', true);
📤

POST Request

Send data to server

xhr.open('POST', 'submit.php', true);
✏️

PUT Request

Update existing data

xhr.open('PUT', 'api/user/123', true);
🗑️

DELETE Request

Remove data from server

xhr.open('DELETE', 'api/user/123', true);

🔹 Making a GET Request

GET requests are used to retrieve data from the server:

function getData() {
    // 1. Create XMLHttpRequest
    const xhr = new XMLHttpRequest();
    
    // 2. Configure GET request
    xhr.open('GET', 'api/products.json', true);
    
    // 3. Handle the response
    xhr.onload = function() {
        if (xhr.status === 200) {
            const data = JSON.parse(xhr.responseText);
            console.log('Products:', data);
            displayProducts(data);
        } else {
            console.error('Error:', xhr.status);
        }
    };
    
    // 4. Send the request (no data needed for GET)
    xhr.send();
}

// Usage
getData(); // Fetches product data

Interactive Demo:

Click to send GET request

🔹 Making a POST Request

POST requests send data to the server:

function sendData() {
    // 1. Create XMLHttpRequest
    const xhr = new XMLHttpRequest();
    
    // 2. Configure POST request
    xhr.open('POST', 'api/users', true);
    
    // 3. Set content type for JSON data
    xhr.setRequestHeader('Content-Type', 'application/json');
    
    // 4. Handle the response
    xhr.onload = function() {
        if (xhr.status === 201) { // 201 = Created
            console.log('User created successfully!');
            const response = JSON.parse(xhr.responseText);
            console.log('New user ID:', response.id);
        } else {
            console.error('Error creating user:', xhr.status);
        }
    };
    
    // 5. Prepare data to send
    const userData = {
        name: 'John Doe',
        email: '[email protected]',
        age: 30
    };
    
    // 6. Send the request with data
    xhr.send(JSON.stringify(userData));
}

// Usage
sendData(); // Creates a new user

Interactive Demo:

Click to send POST request

🔹 Request Headers

Headers provide additional information about your request:

const xhr = new XMLHttpRequest();
xhr.open('POST', 'api/data', true);

// Common headers
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.setRequestHeader('Authorization', 'Bearer your-token-here');
xhr.setRequestHeader('Accept', 'application/json');
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');

// Send request
xhr.send(JSON.stringify({message: 'Hello Server!'}));

📋 Common Headers:

  • Content-Type: What type of data you're sending
  • Accept: What type of response you want
  • Authorization: Authentication credentials
  • User-Agent: Information about your browser
  • X-Requested-With: Identifies AJAX requests

🔹 Handling Form Data

Sending form data with AJAX:

<!-- HTML Form -->
<form id="userForm">
    <input type="text" name="username" placeholder="Username" required>
    <input type="email" name="email" placeholder="Email" required>
    <button type="submit">Submit</button>
</form>

<script>
document.getElementById('userForm').addEventListener('submit', function(e) {
    e.preventDefault(); // Stop normal form submission
    
    // Method 1: Using FormData (easy way)
    const formData = new FormData(this);
    
    const xhr = new XMLHttpRequest();
    xhr.open('POST', 'submit-form.php', true);
    
    xhr.onload = function() {
        if (xhr.status === 200) {
            alert('Form submitted successfully!');
        }
    };
    
    xhr.send(formData); // Send form data
});

// Method 2: Manual data collection
function submitFormManually() {
    const username = document.querySelector('[name="username"]').value;
    const email = document.querySelector('[name="email"]').value;
    
    const data = {
        username: username,
        email: email
    };
    
    const xhr = new XMLHttpRequest();
    xhr.open('POST', 'submit-form.php', true);
    xhr.setRequestHeader('Content-Type', 'application/json');
    
    xhr.onload = function() {
        if (xhr.status === 200) {
            console.log('Success:', xhr.responseText);
        }
    };
    
    xhr.send(JSON.stringify(data));
}
</script>

🔹 Request Timeout and Error Handling

Make your requests more robust:

function robustRequest() {
    const xhr = new XMLHttpRequest();
    
    // Set timeout (5 seconds)
    xhr.timeout = 5000;
    
    xhr.open('GET', 'api/slow-endpoint', true);
    
    // Success handler
    xhr.onload = function() {
        if (xhr.status >= 200 && xhr.status < 300) {
            console.log('Success:', xhr.responseText);
        } else {
            console.error('HTTP Error:', xhr.status, xhr.statusText);
        }
    };
    
    // Timeout handler
    xhr.ontimeout = function() {
        console.error('Request timed out after 5 seconds');
        alert('Request is taking too long. Please try again.');
    };
    
    // Network error handler
    xhr.onerror = function() {
        console.error('Network error occurred');
        alert('Network error. Check your connection.');
    };
    
    // Abort handler
    xhr.onabort = function() {
        console.log('Request was cancelled');
    };
    
    xhr.send();
    
    // You can cancel the request if needed
    // setTimeout(() => xhr.abort(), 3000);
}

🧠 Test Your Knowledge

Which HTTP method is used to retrieve data from the server?