AJAX Response

Handling server responses

📬 What is an AJAX Response?

An AJAX response is the server's reply to your request. It's like getting a letter back with the information you asked for, or confirmation that your message was received!


xhr.onload = function() {
    // The server responded!
    console.log('Status:', xhr.status);        // 200, 404, 500, etc.
    console.log('Response:', xhr.responseText); // The actual data
    console.log('Ready:', xhr.readyState);     // Should be 4
};
                                    

Response contains:

📊 Status code (success/error)

📄 Response data (text, JSON, XML)

📋 Headers (metadata)

Response Properties

🔢

Status Code

HTTP status of the response

xhr.status // 200, 404, 500...
📝

Response Text

Response data as text

xhr.responseText // String data
🏷️

Status Text

Human-readable status

xhr.statusText // "OK", "Not Found"
📋

Response Headers

Metadata about the response

xhr.getAllResponseHeaders()

🔹 HTTP Status Codes

Status codes tell you what happened with your request:

📊 Common Status Codes:

✅ Success (2xx):

  • 200 OK: Request successful
  • 201 Created: Resource created
  • 204 No Content: Success, no data

❌ Error (4xx, 5xx):

  • 400 Bad Request: Invalid request
  • 404 Not Found: Resource not found
  • 500 Server Error: Server problem
xhr.onload = function() {
    // Check status code
    if (xhr.status >= 200 && xhr.status < 300) {
        // Success! (2xx status codes)
        console.log('✅ Success:', xhr.status, xhr.statusText);
        handleSuccess(xhr.responseText);
    } else if (xhr.status === 404) {
        // Not found
        console.log('❌ Not found:', xhr.status);
        showError('The requested resource was not found');
    } else if (xhr.status >= 500) {
        // Server error
        console.log('🔥 Server error:', xhr.status);
        showError('Server is having problems. Try again later.');
    } else {
        // Other error
        console.log('⚠️ Error:', xhr.status, xhr.statusText);
        showError('Something went wrong: ' + xhr.statusText);
    }
};

🔹 Handling JSON Responses

Most modern APIs return JSON data:

function fetchUserData() {
    const xhr = new XMLHttpRequest();
    xhr.open('GET', 'api/user/123', true);
    
    xhr.onload = function() {
        if (xhr.status === 200) {
            try {
                // Parse JSON response
                const user = JSON.parse(xhr.responseText);
                
                console.log('User data:', user);
                console.log('Name:', user.name);
                console.log('Email:', user.email);
                
                // Update the page
                document.getElementById('userName').textContent = user.name;
                document.getElementById('userEmail').textContent = user.email;
                
            } catch (error) {
                console.error('Invalid JSON response:', error);
                showError('Received invalid data from server');
            }
        } else {
            console.error('Failed to fetch user:', xhr.status);
        }
    };
    
    xhr.send();
}

// Example JSON response from server:
// {
//   "id": 123,
//   "name": "John Doe",
//   "email": "[email protected]",
//   "age": 30,
//   "active": true
// }

Interactive Demo:

Click to fetch JSON response

🔹 Handling Text Responses

Simple text responses are easy to work with:

function loadTextFile() {
    const xhr = new XMLHttpRequest();
    xhr.open('GET', 'content/article.txt', true);
    
    xhr.onload = function() {
        if (xhr.status === 200) {
            // Response is plain text
            const textContent = xhr.responseText;
            
            console.log('Text length:', textContent.length);
            console.log('First 100 chars:', textContent.substring(0, 100));
            
            // Display the text
            document.getElementById('article').innerHTML = textContent;
            
            // Or process line by line
            const lines = textContent.split('\n');
            console.log('Number of lines:', lines.length);
            
        } else {
            console.error('Failed to load text file:', xhr.status);
        }
    };
    
    xhr.send();
}

Interactive Demo:

Click to load text response

🔹 Response Headers

Headers provide useful information about the response:

xhr.onload = function() {
    if (xhr.status === 200) {
        // Get all headers
        const allHeaders = xhr.getAllResponseHeaders();
        console.log('All headers:', allHeaders);
        
        // Get specific headers
        const contentType = xhr.getResponseHeader('Content-Type');
        const contentLength = xhr.getResponseHeader('Content-Length');
        const lastModified = xhr.getResponseHeader('Last-Modified');
        
        console.log('Content Type:', contentType);
        console.log('Content Length:', contentLength, 'bytes');
        console.log('Last Modified:', lastModified);
        
        // Handle different content types
        if (contentType.includes('application/json')) {
            const data = JSON.parse(xhr.responseText);
            handleJSONData(data);
        } else if (contentType.includes('text/html')) {
            document.getElementById('content').innerHTML = xhr.responseText;
        } else if (contentType.includes('text/plain')) {
            document.getElementById('content').textContent = xhr.responseText;
        }
    }
};

🔹 Error Handling

Always handle different types of errors:

function robustAjaxRequest() {
    const xhr = new XMLHttpRequest();
    xhr.open('GET', 'api/data', true);
    xhr.timeout = 10000; // 10 second timeout
    
    // Success handler
    xhr.onload = function() {
        if (xhr.status >= 200 && xhr.status < 300) {
            // Success
            try {
                const data = JSON.parse(xhr.responseText);
                handleSuccess(data);
            } catch (e) {
                handleError('Invalid JSON response', e);
            }
        } else {
            // HTTP error
            handleHttpError(xhr.status, xhr.statusText);
        }
    };
    
    // Network error handler
    xhr.onerror = function() {
        handleError('Network error', 'Check your internet connection');
    };
    
    // Timeout handler
    xhr.ontimeout = function() {
        handleError('Request timeout', 'Server is taking too long to respond');
    };
    
    xhr.send();
}

function handleSuccess(data) {
    console.log('✅ Success:', data);
    // Update UI with data
}

function handleHttpError(status, statusText) {
    console.error('❌ HTTP Error:', status, statusText);
    
    switch(status) {
        case 400:
            showMessage('Bad request. Please check your input.');
            break;
        case 401:
            showMessage('Please log in to continue.');
            break;
        case 403:
            showMessage('You don\'t have permission to access this.');
            break;
        case 404:
            showMessage('The requested resource was not found.');
            break;
        case 500:
            showMessage('Server error. Please try again later.');
            break;
        default:
            showMessage('An error occurred: ' + statusText);
    }
}

function handleError(type, message) {
    console.error('⚠️', type + ':', message);
    showMessage(message);
}

function showMessage(message) {
    // Display error message to user
    const errorDiv = document.getElementById('errorMessage');
    errorDiv.textContent = message;
    errorDiv.style.display = 'block';
}

🔹 Complete Response Example

Here's a complete example showing all response handling:

function completeExample() {
    const xhr = new XMLHttpRequest();
    
    // Show loading indicator
    document.getElementById('loading').style.display = 'block';
    document.getElementById('result').innerHTML = '';
    
    xhr.open('GET', 'api/complete-data', true);
    xhr.timeout = 5000;
    
    xhr.onreadystatechange = function() {
        console.log('ReadyState changed to:', xhr.readyState);
        
        if (xhr.readyState === 4) { // Request complete
            // Hide loading indicator
            document.getElementById('loading').style.display = 'none';
            
            console.log('Final status:', xhr.status);
            console.log('Status text:', xhr.statusText);
            console.log('Response headers:', xhr.getAllResponseHeaders());
            
            if (xhr.status === 200) {
                // Success!
                console.log('✅ Request successful');
                console.log('Response:', xhr.responseText);
                
                // Display success message
                document.getElementById('result').innerHTML = 
                    '✅ Success!
Data: ' + xhr.responseText; } else { // Error console.log('❌ Request failed'); document.getElementById('result').innerHTML = '❌ Error: ' + xhr.status + ' ' + xhr.statusText; } } }; xhr.onerror = function() { document.getElementById('loading').style.display = 'none'; document.getElementById('result').innerHTML = '❌ Network error occurred'; }; xhr.ontimeout = function() { document.getElementById('loading').style.display = 'none'; document.getElementById('result').innerHTML = '⏰ Request timed out'; }; xhr.send(); }

Interactive Demo:

Click to see complete response handling

🧠 Test Your Knowledge

What HTTP status code indicates a successful request?