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

Urldecode string (LUA)
FFMPEG Convert YUV444p to YUV420p (BASH)
Forcing FFMPEG to honour segment length in HLS Stream Creator (BASH)
Force CURL to place request to a specific IP (BASH)
Set a variable only if it is undefined (Javascript)
Ignore query string with Nginx caching proxy (NGinx)
Get breakdown of UK and non-UK votes for a Parliamentary Petition (Python)
Decompress Mozilla Firefox jsonlz4 bookmark backup files (Python)
Setting Git author details for a single repo (Git)
Checking Virtual Machine Resource Allocations with Libvirt (BASH)

Copyright © 2019 Ben Tasker | Sitemap | Privacy Policy
Available at snippets.bentasker.co.uk and snippets.6zdgh5a5e6zpchdz.onion