Last active
July 15, 2016 15:56
-
-
Save k1sul1/1e34a2c5eab0f7d903037c0e3e8605e1 to your computer and use it in GitHub Desktop.
Handy helper function to help battle jQuery addiction. [ES6]
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
export function request(options = {}){ | |
// Usage: | |
// request({ | |
// url: "example.com", | |
// data: document.querySelector("form"), //FormData-object or form element | |
// method: "POST", | |
// headers: {key: "value"}, | |
// success: function(response, status){}, | |
// error: function(error, status){}, | |
// progress: function(status){} | |
// }) | |
if(!Object.keys(options).length){ | |
throw Error("Valid arguments required"); | |
} | |
let method = options.method.toUpperCase(); | |
let url = options.url; | |
let data = options.data; | |
let headers = options.headers; | |
let onload = options.success; | |
let onerror = options.error; | |
let onprogress = options.progress; | |
let request = new XMLHttpRequest(); | |
request.open(method, url, true); | |
for(let key in headers){ | |
if(!headers.hasOwnProperty(key)){ | |
continue; | |
} | |
request.setRequestHeader(key, headers[key]); | |
} | |
request.onload = function() { | |
if (request.status >= 200 && request.status < 400) { | |
if(typeof onload === "function"){ | |
onload(request.responseText, request.statusText); | |
} | |
} | |
else { | |
if(typeof onerror === "function"){ | |
onerror(request.responseText, request.statusText); | |
} | |
} | |
}; | |
request.onprogress = function(){ | |
if(typeof onprogress === "function"){ | |
onprogress(request); | |
} | |
}; | |
request.onerror = function(err){ | |
if(typeof onerror === "function"){ | |
onerror(err); | |
} | |
}; | |
if(data instanceof HTMLElement){ | |
// Assume we're dealing with a form here. Take the element and "serialize" it. | |
data = new FormData(data); | |
} | |
if(data){ | |
request.send(data); | |
} | |
else{ | |
request.send(); | |
} | |
return request; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment