Skip to content

Instantly share code, notes, and snippets.

@jesusalber1
Created November 24, 2015 21:38
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 jesusalber1/b0a3a21b555a4294eb21 to your computer and use it in GitHub Desktop.
Save jesusalber1/b0a3a21b555a4294eb21 to your computer and use it in GitHub Desktop.
AJAX request to API with callback
function sendRequest(method, targetURL, content, callback) {
var http = new XMLHttpRequest(),
message = (content !== undefined) ? JSON.stringify(content) : undefined;
http.open(method, targetURL, true);
if (message !== undefined) { /* GET requests may not have JSON content */
http.setRequestHeader('Content-type', 'application/json; charset=utf-8');
}
http.send(message); /* message || undefined */
/* Asynchronous reception */
http.onreadystatechange = function() {
if (http.readyState == 4 && http.status == 200) {
return callback(null, http.responseText);
} else if (http.status != 200 && http.status != 304) {
return callback(http.status);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment