Skip to content

Instantly share code, notes, and snippets.

@pizzarob
Created August 21, 2016 18:45
Show Gist options
  • Save pizzarob/6c9efc583a17c2643505e7d70ffb1e0e to your computer and use it in GitHub Desktop.
Save pizzarob/6c9efc583a17c2643505e7d70ffb1e0e to your computer and use it in GitHub Desktop.
Helper Functions for Making XHR Requests in JavaScript
function post(url, data) {
return new Promise((resolve, reject) => {
let xhr = new XMLHttpRequest();
xhr.open('POST', url);
xhr.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');
xhr.addEventListener('load', () => {
let { response, status } = xhr;
let res = JSON.parse(response);
if(status >= 200 && status < 400){
resolve({ response: res, status });
} else{
reject({ response: res , status });
}
});
xhr.send(JSON.stringify(data));
});
}
function xhr(method, url, data) {
return new Promise((resolve, reject) => {
let xhr = new XMLHttpRequest();
xhr.open(method, url);
xhr.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');
xhr.addEventListener('load', () => {
let { response, status } = xhr;
let res = JSON.parse(response);
if(status >= 200 && status < 400){
resolve({ response: res, status });
} else{
reject({ response: res , status });
}
});
if(data){
xhr.send(JSON.stringify(data));
} else {
xhr.send();
}
});
}
export { post, xhr };
@prince272
Copy link

Thanks Man!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment