Skip to content

Instantly share code, notes, and snippets.

@drew-y
Last active April 17, 2016 22:01
Show Gist options
  • Save drew-y/e2f373cec62c6f209661c949903002a6 to your computer and use it in GitHub Desktop.
Save drew-y/e2f373cec62c6f209661c949903002a6 to your computer and use it in GitHub Desktop.
Simple promise based ajax helper function
/**
* Ajax helper, returns a promise. Assumes both request and response are json.
*/
function ajax(type, url, data) {
return new Promise(function (resolve, reject) {
var req = new XMLHttpRequest();
req.onload = function () {
if (req.status >= 200 && req.status < 400) {
resolve(JSON.parse(req.responseText));
} else {
reject(JSON.parse(req.responseText));
}
};
req.onerror = function () {
reject({success: false, error: 'Network interuption'});
};
req.open(type, url);
if (type === 'PUT' || type === 'POST') {
req.setRequestHeader('Content-Type', 'application/json');
}
req.send(JSON.stringify(data));
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment