Creating a Reusable Ajax Function in JavaScript

The core of a custom Ajax utility involves creaitng an XMLHttpRequest object and managing its lifecycle. Below is a function designed to handle asynchrnoous HTTP requests with configuration options.

/**
 * Configuration object structure for the custom Ajax function.
 * @typedef {Object} AjaxConfig
 * @property {string} method - HTTP request method (e.g., 'get', 'post').
 * @property {Object} payload - Data to be sent with the request.
 * @property {Object} headers - Key-value pairs for HTTP headers.
 * @property {string} endpoint - The target URL for the request.
 * @property {Function} onSuccess - Callback function invoked on a successful response.
 * @property {Function} onFailure - Callback function invoked on a request failure.
 */

function performRequest(config) {
    // Initialize the HTTP request object
    const request = new XMLHttpRequest();

    // Process and format the request data
    let formattedData = '';
    for (const key in config.payload) {
        formattedData += `${key}=${config.payload[key]}&`;
    }
    // Remove the trailing '&' character
    formattedData = formattedData.slice(0, -1);

    // Handle GET request URL formatting
    if (config.method.toLowerCase() === 'get') {
        config.endpoint = `${config.endpoint}?${formattedData}`;
    }

    // Configure the request with method and URL
    request.open(config.method, config.endpoint);

    // Set headers and send data for POST requests
    if (config.method.toLowerCase() === 'post') {
        const contentType = config.headers['Content-Type'];
        if (contentType) {
            request.setRequestHeader('Content-Type', contentType);
        }
        // Determine the data format to send
        if (contentType === 'application/json') {
            request.send(JSON.stringify(config.payload));
        } else {
            request.send(formattedData);
        }
    } else {
        // Send the request for non-POST methods
        request.send();
    }

    // Define the handler for when the request completes
    request.onload = function() {
        const responseHeader = request.getResponseHeader('Content-Type');
        let serverResponse = request.responseText;

        // Parse JSON response if the header indicates it
        if (responseHeader && responseHeader.includes('application/json')) {
            serverResponse = JSON.parse(serverResponse);
        }

        // Execute the appropriate callback based on HTTP status
        if (request.status === 200) {
            config.onSuccess(serverResponse);
        } else {
            config.onFailure(serverResponse, request);
        }
    };
}

Here is an example demonstratign how to use the function:

<!DOCTYPE html>
<html>
<body>
    <h2>Ajax Function Demo</h2>
    <button id="requestButton">Send Test Request</button>

    <script>
        document.getElementById('requestButton').addEventListener('click', function() {
            performRequest({
                method: 'post',
                payload: {
                    username: 'demoUser',
                    id: 101
                },
                headers: {
                    'Content-Type': 'application/json'
                },
                endpoint: 'https://api.example.com/data',
                onSuccess: function(responseData) {
                    console.log('Request succeeded:', responseData);
                },
                onFailure: function(errorData, requestObj) {
                    console.log(`Request failed with status ${requestObj.status}:`, errorData);
                }
            });
        });
    </script>
</body>
</html>

Tags: javascript Ajax XMLHttpRequest HTTP Requests Frontend Development

Posted on Fri, 08 May 2026 22:13:03 +0000 by asmon