JSFiddle - React, Tailwind, and code Playground

by LyndseyB

JavaScript

var ajaxRequest = function ajaxRequest(url, data, callback, method) {
	method = method || 'POST';
  
  // validate that the method passed exists
  switch(method.toUpperCase()) {
  	case 'GET':
    case 'POST':
    	break;
    default:
    	throw('Invalid ajax method requested');
  }
  
	var request = new XMLHttpRequest();
  
  if(!request) {
  	throw('Cannot create HttpRequest instance');
    return;
  }
  
  // run callback when request state changes
  if(callback && typeof callback === 'function') {  
  	request.onreadystatechange = callback.bind(null, request);
  }
  
  request.open(method, url);
  request.send();
};

ajaxRequest('/test/url', { name: 'Lyndsey' }, function(request, data) {
	if (request.readyState === XMLHttpRequest.DONE) {
  	if (request.status === 200) {
    	console.log('request was successful');
    }
  }
  else {
  	console.warn('Request returned an invalid status code: ', request.status);
  }
});