Place AJAX GET request and trigger callback function with result (Javascript)

Simple Javascript function to place a xmlhttp request (supporting a range of browsers) and trigger a callback function once the request has been satisfied

This is one of the functions I often find myself looking at older projects to find rather than re-writing it. Yes you can do the same with jQuery, but that's only really a valid route if you're already loading jQuery. Otherwise you're loading an entire framework for no real benefit

Similar To

  • jQuery.get()

Details

Snippet

function fetchPage(url,callback,errcallback){
    var xmlhttp;
    if (window.XMLHttpRequest){
        // code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp=new XMLHttpRequest();
    }else{
        // code for IE6, IE5 (why am I still supporting these? Die... Die.... Die....
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }

    xmlhttp.onreadystatechange=function(){
        if (xmlhttp.readyState==4){
     if (xmlhttp.status==200){
        callback(xmlhttp.responseText)
            }else{
               errcallback(xmlhttp.responseText)
            }
       }
    }

    xmlhttp.open("GET",url,true);
    xmlhttp.send();
}

Usage Example

var success = alert;
var error = console.log;
fetchJSON('sitemap.json',success,error);