Skip to content

Instantly share code, notes, and snippets.

@scruwys
Created February 16, 2015 20:10
Show Gist options
  • Select an option

  • Save scruwys/384eef2198a5f7b82233 to your computer and use it in GitHub Desktop.

Select an option

Save scruwys/384eef2198a5f7b82233 to your computer and use it in GitHub Desktop.
async requests in JavaScript
// 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));
};
// 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