JSFiddle - React, Tailwind, and code Playground

by BurpmanJunior

JavaScript

/**
 * Flexible AJAX request with callback
 * @param  {object} options url|data|method|async|load
 */
function _xhr(options){
  var XHR,
      PARAMS,
      callback;

  // Throw invalid
  if(typeof options !== 'object'){
    return false;
  }
  if(typeof options.url !== 'string'){
    return false;
  }

  // Method
  if(typeof options.method !== 'string'){
    // Set default
    options.method = 'GET';
  }else{
    options.method = options.method.toUpperCase();
  }

  // Initialize
  XHR = new XMLHttpRequest();
  XHR.open(options.method, options.url, options.async);

  // Data object to string
  if(typeof options.data === 'object'){
    for(key in options.data){
      PARAMS += '&' + encodeURIComponent(key) + '=' + encodeURIComponent(options.data[key]);
    }
    PARAMS = PARAMS.replace(/^&/, '?');
  }

  // Data and headers
  if(options.method == 'POST'){
    XHR.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    //XHR.setRequestHeader("Connection", "closed");
    //XHR.setRequestHeader("Content-length", PARAMS.length);
  }
  if(options.method == 'GET'){
    options.url += (PARAMS ? PARAMS : '');
  }

  // Calls callback if available;
  callback = function(){
    if(typeof options.load === 'function'){
      options.load.call(this);
    }
  }

  // Asynchronous
  if(typeof options.async !== 'boolean'){
    // Set default
    options.async = true;
  }

  // Execute
  XHR.onreadystatechange = function(){
    if(XHR.readyState == 4 && XHR.status == 200){
      callback.call(XHR);
    }
  }
  XHR.send(PARAMS);
}

// Demo
_xhr({
	url: 'https://fiddle.jshell.net',
  method: 'GET',
  load: function(){
  	document.body.innerHTML += 'Loaded: ' + this.responseURL;
  }
});