Created
November 24, 2015 21:38
-
-
Save jesusalber1/b0a3a21b555a4294eb21 to your computer and use it in GitHub Desktop.
AJAX request to API with callback
This file contains 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
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