How do I make AJAX requests

This example demonstrates how to make AJAX requests in JavaScript using both XMLHttpRequest and fetch API.
AJAX, JavaScript, XMLHttpRequest, fetch API

// Using XMLHttpRequest
var xhr = new XMLHttpRequest();
xhr.open('GET', 'https://api.example.com/data', true);
xhr.onload = function () {
    if (xhr.status >= 200 && xhr.status < 300) {
        console.log('Response:', xhr.responseText);
    } else {
        console.error('Request failed with status:', xhr.status);
    }
};
xhr.onerror = function () {
    console.error('Request failed');
};
xhr.send();

// Using fetch API
fetch('https://api.example.com/data')
    .then(response => {
        if (!response.ok) {
            throw new Error('Network response was not ok ' + response.statusText);
        }
        return response.json();
    })
    .then(data => console.log('Data:', data))
    .catch(error => console.error('There was a problem with the fetch operation:', error));
    

AJAX JavaScript XMLHttpRequest fetch API