puiu91
3/24/2016 - 2:09 PM

Ajax

Ajax

function retrieveAjaxData() {
    var xhr = new XMLHttpRequest();
    xhr.open('POST', encodeURI('/'), true);
    xhr.setRequestHeader('Content-Type', 'application/json');
    xhr.onreadystatechange = function() {
        if (xhr.readyState === 4) {
            
            var returnedData = JSON.parse(xhr.responseText)
            
            if (xhr.status === 200) {
                doSomething()
            } else if (xhr.status === 204) { // no data returned but successful ajax request otherwise
                return;
            } else {
                throw 'ajax request failed'; // for all intents and purposes, the ajax request has failed
            }
        
            alwaysDoThis();
        }
    };

    xhr.send();
}

http://www.html5rocks.com/en/tutorials/file/xhr2/

  var xhr = new XMLHttpRequest();
  xhr.open('POST', encodeURI('ajax/logger.php'), true);
  xhr.setRequestHeader('Content-Type', 'application/json');
  xhr.responseType = 'text';

  xhr.onload = function(e) {
    if (this.status == 200) {
      console.log('REQUEST RETURNED 200 RESPONSE');
      console.dir(this.response);
    }
  };

  xhr.send(JSON.stringify(data));
}