JavaScript xhr Request

01/30/2024
Back to Gists
/**
 * JavaScript Request with Error Handling
 * Author: Knol Aust
 * Gist Keywords: js, javascript, http request, error handling
 * Description: This code checks for the existence of an HTML element with the id "elem" and makes an XMLHttpRequest to an API or endpoint.
 *              It handles both successful responses and errors by providing comments and suggestions.
 */

// Check if the element with id "elem" exists in the page
if (document.getElementById("elem")) {
  // Set the API or endpoint URL
  const endpoint = 'https://the-url.com';
  
  // Set up an XMLHttpRequest object for making HTTP requests
  let xhr = new XMLHttpRequest();
  
  // Define the event handler for when the request completes
  xhr.onload = function () {
    // Check if the HTTP status code indicates success (between 200 and 299)
    if (xhr.status >= 200 && xhr.status < 300) {
      // Code to run when the request is successful
      
      // Parse the response data as JSON to work with it as an object
      const data = JSON.parse(xhr.responseText);
      
      // You can now work with the 'data' object, e.g., call functions, loop through variables, etc.
  		
    } else {
      // Code to run when there is an error in the request
      // It's a good practice to handle errors gracefully, e.g., by hiding the parent element with id "elem"
      // console.log('There was an error. Something is messed up.');
    }
  };
  
  // Create and send a GET request to the specified endpoint
  xhr.open('GET', endpoint);
  xhr.send();
}