AJAX XMLHttp
Making HTTP Requests: Fetch API and XMLHttpRequest
Section titled “Making HTTP Requests: Fetch API and XMLHttpRequest”To exchange data with a server asynchronously, JavaScript needs a mechanism to send HTTP requests and receive responses. The modern standard is the Fetch API, while the older XMLHttpRequest object is still available for legacy purposes.
The Fetch API (Recommended)
Section titled “The Fetch API (Recommended)”The Fetch API provides a modern, powerful, and flexible interface for making HTTP requests. It’s Promise-based, making asynchronous code easier to manage.
Basic syntax for a GET request:
fetch('/api/data') // URL of the resource .then(response => { // Check if the request was successful if (!response.ok) { throw new Error(`HTTP error! status: ${response.status}`); } return response.json(); // Or response.text(), etc. }) .then(data => { console.log(data); // Process the data }) .catch(error => { console.error('There was a problem with the fetch operation:', error); });Key advantages of Fetch:
- Promise-based: Integrates seamlessly with
async/awaitand modern JavaScript patterns. - More flexible: Offers finer control over request and response details (headers, cache, mode, etc.).
- Cleaner API: Generally considered easier to use for common tasks.
- Standardized: The modern standard supported in all current browsers.
We will primarily use the Fetch API throughout this tutorial.
The XMLHttpRequest Object (Legacy)
Section titled “The XMLHttpRequest Object (Legacy)”XMLHttpRequest (XHR) is the older mechanism for making asynchronous requests. While fully supported by modern browsers, it’s generally more verbose and uses an event-based model (onreadystatechange) instead of Promises.
Creating an XMLHttpRequest object:
// All modern browsers (Chrome, Firefox, Edge, Safari, Opera, IE7+)const xhr = new XMLHttpRequest();console.log('XMLHttpRequest object created.');
// --- Code for very old IE versions (IE5, IE6) is no longer needed ---// The ActiveXObject approach is obsolete and should not be used.The complex conditional logic to check for window.XMLHttpRequest vs ActiveXObject is no longer necessary for any reasonably modern web development. All relevant browsers support new XMLHttpRequest() directly.
Using XHR involves:
- Creating an instance:
const xhr = new XMLHttpRequest(); - Opening the request:
xhr.open('GET', '/api/data', true);(method, URL, async flag -trueis essential) - Setting up event listeners: Primarily
onreadystatechangeto track progress and handle completion, and optionallyonload,onerror,onprogress. - Sending the request:
xhr.send();
Example using XHR (basic GET):// --- LEGACY XHR EXAMPLE ---const xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() { if (xhr.readyState === XMLHttpRequest.DONE) { // readyState 4 means request finished if (xhr.status === 200) { // status 200 means 'OK' console.log('XHR Response Text:', xhr.responseText); // Process responseText (e.g., parse if it's JSON) try { const data = JSON.parse(xhr.responseText); console.log('Parsed XHR JSON:', data); } catch(e) { console.error('Error parsing JSON:', e); } } else { console.error('XHR Request failed with status:', xhr.status); } }};
xhr.onerror = function() { console.error('XHR Network error occurred');};
xhr.open('GET', '/api/data', true);xhr.send(); // For GET requests, send() takes no arguments or nullWhile you might encounter XHR in older code or specific scenarios (like monitoring upload progress, which Fetch handles differently), Fetch is the recommended approach for new development.
The next chapters will focus on using the Fetch API to send requests and handle responses.