Last active
April 17, 2016 22:01
-
-
Save drew-y/e2f373cec62c6f209661c949903002a6 to your computer and use it in GitHub Desktop.
Simple promise based ajax helper function
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
/** | |
* 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