Plain Javascript AJAX request demo

by GRMule

HTML

<a href="#" onclick="return getSuccessOutput();"> test success </a> | <a href="#" onclick="return getFailOutput(); return false;"> test failure</a>
<div id="output">waiting for action</div>

CSS

a {
    padding: 0.2em;
}
a:hover {
    background-color: #02AAEE;
}
#output {
    display: block;
    margin-top: 8px;
    padding: 1%;
    border: 1px solid #666;
    background-color: #efefef;
    
}

JavaScript

// handles the click event for link 1, sends the query
function getSuccessOutput() {
  getRequest(
      '/echo/js/?js=hello%20world!', // demo-only URL
       drawOutput,
       drawError
  );
  return false;
}

// handles the click event for link 2, sends the query
function getFailOutput() {
  getRequest(
      'invalid url will fail', // demo-only URL
       drawOutput,
       drawError
  );
  return false;
}

// handles drawing an error message
function drawError () {
    var container = document.getElementById('output');
    container.innerHTML = 'Bummer: there was an error!';
}
// handles the response, adds the html
function drawOutput(responseText) {
    var container = document.getElementById('output');
    container.innerHTML = responseText;
}
// helper function for cross-browser request object
function getRequest(url, success, error) {
    var req = false;
    try{
        // most browsers
        req = new XMLHttpRequest();
    } catch (e){
        // IE
        try{
            req = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {
            // try an older version
            try{
                req = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e){
                return false;
            }
        }
    }
    if (!req) return false;
    if (typeof success != 'function') success = function () {};
    if (typeof error!= 'function') error = function () {};
    req.onreadystatechange = function(){
        if(req .readyState == 4){
            return req.status === 200 ? 
                success(req.responseText) : error(req.status)
            ;
        }
    }
    req.open("GET", url, true);
    req.send(null);
    return req;
}