📚 The loadDoc() Function: AJAX Implementations

1. Basic loadDoc() Function (Original)

The classic implementation using XMLHttpRequest

function loadDoc() {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      document.getElementById("demo").innerHTML = this.responseText;
    }
  };
  xhttp.open("GET", "ajax_info.txt", true);
  xhttp.send();
}
Click button to load content here

2. Enhanced loadDoc() with Parameters

More flexible version that accepts URL and target element

function loadDoc(url, elementId, callback) {
  var xhr = new XMLHttpRequest();
  xhr.onreadystatechange = function() {
    if (xhr.readyState === 4) {
      if (xhr.status === 200) {
        document.getElementById(elementId).innerHTML = xhr.responseText;
        if (callback) callback(null, xhr.responseText);
      } else {
        if (callback) callback('Error: ' + xhr.status, null);
      }
    }
  };
  xhr.open("GET", url, true);
  xhr.send();
}
Enhanced version will load content here

3. Modern loadDoc() with Fetch API

Using modern JavaScript Fetch API with async/await

async function loadDocModern(url, elementId, options = {}) {
  try {
    const response = await fetch(url, options);
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }
    const data = await (options.json ? response.json() : response.text());
    document.getElementById(elementId).innerHTML = formatData(data, options.json);
    return data;
  } catch (error) {
    document.getElementById(elementId).innerHTML = `<p style="color: red;">Error: ${error.message}</p>`;
    throw error;
  }
}
Modern Fetch API results will appear here

4. Complete AJAX Utility Library

A comprehensive loadDoc() implementation with all features

// Complete AJAX utility class
class AjaxLoader {
  constructor(baseURL = '') {
    this.baseURL = baseURL;
    this.requests = {};
  }

  loadDoc(url, options = {}) {
    const config = {
      method: options.method || 'GET',
      headers: options.headers || {},
      body: options.body,
      timeout: options.timeout || 30000,
      responseType: options.responseType || 'text',
      onProgress: options.onProgress,
      onSuccess: options.onSuccess,
      onError: options.onError
    };
    // Implementation continues...
  }
}
AJAX Library test results