Last active
June 15, 2017 19:43
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* 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