Skip to content

Instantly share code, notes, and snippets.

@lucasmenendez
Last active September 10, 2017 15:14
Show Gist options
  • Save lucasmenendez/a4947b6222285a3fa4530a111bcc3cf2 to your computer and use it in GitHub Desktop.
Save lucasmenendez/a4947b6222285a3fa4530a111bcc3cf2 to your computer and use it in GitHub Desktop.
<script src="http.js"></script>
<script src="example.js"></script>
//Example
var url = "http://jsonplaceholder.typicode.com/posts",
json = true,
data = {
title: "Example",
body: "Hello world!",
userId: 1917
};
http.post(url, json, data, function (res) {
if (res.success) {
console.log(res.data);
} else {
console.log("Error!");
}
}, function(progress) {
console.log(progress.completed + "% completed.");
});
var http = {
get: function(u, j, d, c, p) { this.call("GET", u, j, d, c, p); },
post: function(u, j, d, c, p) { this.call("POST", u, j, d, c, p); },
put: function(u, j, d, c, p) { this.call("PUT", u, j, d, c, p); },
delete: function(u, j, d, c, p) { this.call("DELETE", u, j, d, c, p); },
options: function(u, j, d, c, p) { this.call("OPTIONS", u, j, d, c, p); },
call: function (method, uri, json, data, callback, progress) {
var req = new XMLHttpRequest();
req.open(method, uri, true);
var payload = new FormData();
for (var key in data) {
if (data.hasOwnProperty(key)) {
var value = data[key];
payload.append(key, value);
}
}
req.send(payload);
req.onprogress = function(e) {
if (e.lengthComputable) {
progress({
loaded: e.loaded,
total: e.total,
completed: (e.loaded/e.total)*100
});
}
};
req.onreadystatechange = function() { //Response handler
if (req.readyState === 4) { //Done
var res = (json) ? JSON.parse(req.responseText) : req.responseText;
callback({
success: (300 >= req.status && req.status >= 200), //Ok
data: res
});
}
}
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment