Created
February 16, 2015 20:10
-
-
Save scruwys/384eef2198a5f7b82233 to your computer and use it in GitHub Desktop.
async requests in JavaScript
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
| // needs better support for 4xx responses, but a good starting off point... | |
| var ajax = {}; | |
| ajax.build_payload = function(data) { | |
| var payload = []; | |
| // prepare to pass variables as URL string... | |
| for( var n in data ) { | |
| payload.push(encodeURIComponent(n) + '=' + encodeURIComponent(data[n])); | |
| }; | |
| return payload.join("&"); | |
| }; | |
| ajax.get = function(route, data, callback) { | |
| var xhr = new XMLHttpRequest(); | |
| xhr.open("GET", route + '?' + ajax.build_payload(data), true); | |
| xhr.onload = function() { | |
| var response = JSON.parse(xhr.responseText); | |
| var status = xhr.status; | |
| callback(response, status); | |
| }; | |
| xhr.onerror = function() { | |
| // perform action on error... | |
| }; | |
| xhr.send(); | |
| }; | |
| ajax.post = function(route, data, callback) { | |
| // could probably abstract XMLHttpRequest and xhr.send() to it's own method to be DRYer... | |
| var xhr = new XMLHttpRequest(); | |
| xhr.open("POST", route, true); | |
| xhr.onload = function() { | |
| var response = JSON.parse(xhr.responseText), | |
| var status = xhr.status; | |
| callback(response, status); | |
| }; | |
| xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8"); | |
| xhr.send(ajax.build_payload(data)); | |
| }; |
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
| // GET request | |
| ajax.get('http://api.example.com/users', {}, function(response, status) { | |
| console.log(response); | |
| console.log(status); | |
| }); | |
| // POST request | |
| ajax.post('http://api.example.com/users', {'name': 'Gerald Garner'}, function(response, status) { | |
| console.log(response); | |
| console.log(status); | |
| }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment