Okay, here's a JavaScript function using the traditional XMLHttpRequest (XHR) object to send an HTTP request, receive a response, and decode it assuming it's JSON.
This version uses a standard callback pattern (callback(error, data)) which was common before Promises became widespread.
/**
* Sends an XMLHttpRequest (XHR) to a specified URL and decodes the JSON response.
*
* @param {string} method - The HTTP method (e.g., 'GET', 'POST', 'PUT', 'DELETE').
* @param {string} url - The URL of the API endpoint.
* @param {object|null} data - The data payload to send (for POST/PUT requests).
* Will be JSON.stringify'd. Pass null for GET/DELETE.
* @param {function(Error|null, object|null)} callback - The function to call when the request
* completes or fails.
* - First argument: An Error object if an error occurred, otherwise null.
* - Second argument: The parsed JSON data if successful, otherwise null.
* @param {number} [timeout=10000] - Optional timeout in milliseconds (default: 10000ms).
*/
function sendXhrJsonRequest(method, url, data, callback, timeout = 10000) {
// 1. Create a new XHR object
const xhr = new XMLHttpRequest();
// 2. Configure the request (method, URL, async)
// true means asynchronous
xhr.open(method.toUpperCase(), url, true);
// 3. Set Request Headers
// - Tell the server we accept JSON responses
xhr.setRequestHeader('Accept', 'application/json');
// - If sending data (POST/PUT), set Content-Type to application/json
// and prepare the data payload.
let requestBody = null;
const methodUpper = method.toUpperCase();
if (data && (methodUpper === 'POST' || methodUpper === 'PUT' || methodUpper === 'PATCH')) {
try {
xhr.setRequestHeader('Content-Type', 'application/json;charset=UTF-8');
requestBody = JSON.stringify(data);
} catch (stringifyError) {
console.error("Failed to stringify request data:", stringifyError);
// Immediately call back with the error
// Use setTimeout to ensure callback is always async
setTimeout(() => callback(new Error(`Failed to stringify request data: ${stringifyError.message}`), null), 0);
return; // Stop execution
}
}
// 4. Set up event listeners for the response
// --- onload: Fires when the request completes successfully (status 2xx/3xx) ---
xhr.onload = function() {
// Check for successful HTTP status codes
if (xhr.status >= 200 && xhr.status < 300) {
try {
// Attempt to parse the response text as JSON
const jsonData = JSON.parse(xhr.responseText);
// Success: Call callback with null error and parsed data
callback(null, jsonData);
} catch (parseError) {
// JSON parsing failed
console.error("Failed to parse JSON response:", parseError);
console.error("Raw response text:", xhr.responseText);
callback(new Error(`JSON Parse Error: ${parseError.message}`), null);
}
} else {
// Request completed, but with an error status (4xx, 5xx)
callback(new Error(`HTTP Error: ${xhr.status} ${xhr.statusText}`), null);
}
};
// --- onerror: Fires when there's a network-level error ---
// (e.g., DNS resolution failure, connection refused)
xhr.onerror = function() {
callback(new Error('Network Error occurred'), null);
};
// --- ontimeout: Fires if the request takes longer than the specified timeout ---
xhr.timeout = timeout; // Set the timeout
xhr.ontimeout = function() {
callback(new Error(`Request Timed Out after ${timeout}ms`), null);
};
// 5. Send the request
// - Pass the requestBody (null for GET/DELETE, stringified JSON for POST/PUT)
xhr.send(requestBody);
}
// --- Example Usage ---
// Example 1: GET request
const apiUrlGet = 'https://jsonplaceholder.typicode.com/posts/1'; // Example API
console.log(`Sending GET request to ${apiUrlGet}...`);
sendXhrJsonRequest('GET', apiUrlGet, null, (error, data) => {
if (error) {
console.error('GET Request Failed:', error);
} else {
console.log('GET Request Successful. Data:', data);
}
});
// Example 2: POST request
const apiUrlPost = 'https://jsonplaceholder.typicode.com/posts'; // Example API
const postData = {
title: 'foo',
body: 'bar',
userId: 1,
};
console.log(`Sending POST request to ${apiUrlPost}...`);
sendXhrJsonRequest('POST', apiUrlPost, postData, (error, data) => {
if (error) {
console.error('POST Request Failed:', error);
} else {
// Note: jsonplaceholder returns the created object with an ID
console.log('POST Request Successful. Response Data:', data);
}
});
// Example 3: Request to a non-existent URL (will cause network error or 404)
// const badUrl = 'https://invalid-domain-xyz-123.com/api/data';
// console.log(`Sending GET request to ${badUrl}...`);
// sendXhrJsonRequest('GET', badUrl, null, (error, data) => {
// if (error) {
// console.error('Bad URL Request Failed:', error); // Expected outcome
// } else {
// console.log('Bad URL Request Successful. Data:', data);
// }
// });
Explanation:
XMLHttpRequest Object: Creates an instance of the XHR object.
xhr.open(): Initializes the request.
method: The HTTP verb (GET, POST, etc.). Converted to uppercase for consistency.
url: The target endpoint.
true: Makes the request asynchronous (non-blocking), which is almost always desired in web development.
xhr.setRequestHeader(): Sets HTTP headers.
Accept: application/json: Tells the server that your client prefers to receive data in JSON format.
Content-Type: application/json;charset=UTF-8: Crucially, this is set only when sending data (POST, PUT, PATCH). It tells the server that the body of your request is JSON.
JSON.stringify(data): If data is provided for POST/PUT/PATCH, it's converted into a JSON string before sending. Includes error handling in case the data cannot be stringified.
xhr.onload: This event handler is called when the request finishes successfully (including HTTP errors like 404, 500).
- It checks
xhr.status (the HTTP status code). Codes 200-299 generally indicate success.
- If successful, it tries to parse
xhr.responseText using JSON.parse().
- A
try...catch block handles potential errors if the response isn't valid JSON.
- The
callback is called with (null, parsedData) on success or (error, null) if parsing fails or the HTTP status is an error.
xhr.onerror: This handles network-level errors (e.g., the server is down, DNS lookup fails). The callback is called with (error, null).
xhr.timeout / xhr.ontimeout: Sets a maximum time for the request and provides a handler if it times out.
xhr.send(requestBody): Sends the request. For GET/DELETE, requestBody will be null. For POST/PUT/PATCH, it will be the JSON string.
- Callback: The function uses a callback
(error, data) to return results asynchronously. This is a common pattern in older JavaScript or Node.js code.
Important Considerations:
- Modern Alternative (
fetch): While XHR works, the modern standard for making HTTP requests in browsers (and Node.js) is the fetch API. It's Promise-based and generally has a cleaner, more powerful syntax. You should prefer fetch for new development unless you have specific reasons (like needing upload progress events, which are slightly easier with XHR, or supporting very old browsers).
- Error Handling: The example includes basic error handling for network issues, timeouts, non-2xx HTTP statuses, and JSON parsing errors. Robust applications often require more specific error handling.
- CORS: If you are making requests from a web page to a different domain than the one hosting the page, you'll need the server to support Cross-Origin Resource Sharing (CORS) by sending appropriate
Access-Control-Allow-Origin headers.