Skip to content

Instantly share code, notes, and snippets.

@edm00se
Last active June 15, 2017 19:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save edm00se/385dd5b86552e9b1de71 to your computer and use it in GitHub Desktop.
Save edm00se/385dd5b86552e9b1de71 to your computer and use it in GitHub Desktop.
Vanilla JS function to perform a GET XMLHttpRequest against a passed URL and execute the callback function with the returned results. On error, puts an error message to the console and returns null to the callback.
/*
* Note: these days you should probably just use fetch:
* https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API
*
* A convenience function, to handle the vanilla js xhr
* request.
*
* @param {string} url - the URI against which to make the request
* @param callback - the callback function, which returns an obj,
* with two params, err (which is null of not error), and
* data, which returns the received content, for a successful
* GET request
*
*/
var xhrGet = function(url, callback(err, data)){
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(data){
if( xhr.readyState === XMLHttpResponse.DONE ){
if( xhr.status === 200 ){
callback(null,xhr.responseText);
}else{
throw new Error('Error with xhrGet: '+this);
console.log('XHR error: '+xhr.status);
callback(true,null);
}
}
}
xhr.open('GET', url);
xhr.send();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment