Last active
March 20, 2017 18:52
-
-
Save jacobgardner/b8ad19bcacf336b4eb27ada802cc94b8 to your computer and use it in GitHub Desktop.
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 request(method, endpoint, {payload, headers: {}} = {}) { | |
return new Promise((resolve, reject) => { | |
const ajaxRequest = new XMLHTTPRequest(); | |
ajaxRequest.open(method, endpoint); | |
for (const key of Object.keys(headers)) { | |
ajaxRequest.setRequestHeader(key, headers[key]); | |
} | |
ajaxRequest.onreadystatechange = () => { | |
if(ajaxRequest.readyState === 4) { | |
if (ajaxRequest.status >= 400) { | |
reject(new Error(ajaxRequest.responseText)); | |
} else { | |
resolve(ajaxRequest); | |
} | |
} | |
}; | |
if (payload) { | |
ajaxRequest.send(payload); | |
} else { | |
ajaxRequest.send(); | |
} | |
}); | |
} | |
request('POST', 'thatEndpoint.php', { | |
headers: { | |
'Content-Type': 'multipart/form-data', | |
} | |
}).then((response) => { | |
if (response.status === 302) { | |
const newLocation = response.getResponseHeader('Location'); | |
// redirect or whatever | |
} else { | |
// Show errors from response. | |
} | |
}).catch((err) => { | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment