Created
August 21, 2016 18:45
-
-
Save pizzarob/6c9efc583a17c2643505e7d70ffb1e0e to your computer and use it in GitHub Desktop.
Helper Functions for Making XHR Requests in JavaScript
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 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 }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks Man!