Last active
September 16, 2024 17:23
-
-
Save imshvc/c25e2b681782cd2f200c65bc1df5fb32 to your computer and use it in GitHub Desktop.
Asynchronous XMLHttpRequest abstraction
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Asynchronous XMLHttpRequest abstraction. | |
* @author Nurudin Imsirovic <[email protected]> | |
* @param {string} requestMethod - HTTP Request Method [GET, POST, PUT, DELETE, HEAD, OPTIONS, PATCH] | |
* @param {string} requestSource - URL or relative path to a resource | |
* @param {string} requestData - Data to be sent (only for POST method) | |
* @param {function} callback - Callback function for handling the response | |
* @param {string|null} requestUsername - HTTP Basic Auth Username (default `null`) | |
* @param {string|null} requestPassword - HTTP Basic Auth Password (default `null`) | |
* @throws {Error} Throws an error if XMLHttpRequest is not supported or if the callback is not a function. | |
*/ | |
function xhr( | |
requestMethod = 'GET', | |
requestSource = '', | |
requestData = '', | |
callback, | |
requestUsername = null, | |
requestPassword = null | |
) { | |
// Check for XMLHttpRequest support | |
if (!window.XMLHttpRequest) { | |
throw new Error('XMLHttpRequest is not supported'); | |
} | |
// Validate callback function | |
if (typeof callback !== 'function') { | |
throw new Error('callback must be a function'); | |
} | |
// Supported request methods | |
const supportedMethods = ['GET', 'POST', 'PUT', 'DELETE', 'HEAD', 'OPTIONS', 'PATCH']; | |
requestMethod = requestMethod.trim().toUpperCase(); | |
// Validate request method | |
if (!supportedMethods.includes(requestMethod)) { | |
throw new Error(`Request method "${requestMethod}" is not supported`); | |
} | |
// Create XHR instance | |
const xhrInstance = new XMLHttpRequest(); | |
xhrInstance.responseType = 'text'; | |
// Set headers for POST requests | |
if (requestMethod == 'POST') { | |
xhrInstance.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); | |
} | |
// Open request | |
xhrInstance.open(requestMethod, requestSource, true, requestUsername, requestPassword); | |
// Set up the callback for ready state changes | |
xhrInstance.onreadystatechange = function() { | |
callback(xhrInstance); | |
}; | |
// Send the request | |
xhrInstance.send(requestMethod == 'POST' ? requestData : null); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment