Place AJAX GET request and trigger callback function with result



Published: 2017-08-04 22:19:26 +0000
Categories: Javascript,

Language

Javascript

Description

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()

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);

License

BSD-3-Clause

Keywords

AJAX, xmlhttp, GET, Ecmascript, request,

Latest Posts


Copyright © 2022 Ben Tasker | Sitemap | Privacy Policy
Available at snippets.bentasker.co.uk, http://phecoopwm6x7azx26ctuqcp6673bbqkrqfeoiz2wwk36sady5tqbdpqd.onion and http://snippets.bentasker.i2p
hit counter