« Back to Index

Simple XHR function

View original Gist on GitHub

Tags: #js

simple xhr function.js

function request(url, params, callback) {
  /*
  var params = 'pass=' + encodeURIComponent(password.value) +
               '&encval=' + encodeURIComponent(encval.value) +
               '&code=' + encodeURIComponent(code.value) +
               '&username=' + encodeURIComponent(username.value) +
               '&_xsrf=' + encodeURIComponent(xsrf);
  */
  
  var xhr = new XMLHttpRequest();

  xhr.open('POST', url, true);
  xhr.setRequestHeader('content-type', 'application/x-www-form-urlencoded');

  xhr.onreadystatechange = function() {
    if (xhr.readyState == 4) {
      if (xhr.status == 500) {
        return callback({
          'state': 'error',
          'message': 'There was a problem processing this request.'
        });
      }
      var response = JSON.parse(xhr.responseText);
      return callback(response);
    }
  };

  xhr.send(params);
}