Skip to content

Instantly share code, notes, and snippets.

@christianmendoza
Last active February 24, 2016 20:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save christianmendoza/3da722a1286cd1ce810e to your computer and use it in GitHub Desktop.
Save christianmendoza/3da722a1286cd1ce810e to your computer and use it in GitHub Desktop.
/* http://idiallo.com/javascript/ajax-without-jquery */
var url = "http://jsonplaceholder.typicode.com/posts";
var Ajax = {
xhr : null,
request : function (url, method, data, success, failure) {
if (!this.xhr) {
this.xhr = new XMLHttpRequest();
}
var self = this.xhr;
self.onreadystatechange = function () {
if (self.readyState === 4 && self.status === 200) {
// the request is complete, parse data and call callback
var response = JSON.parse(self.responseText);
success(response);
}
else if (self.readyState === 4) { // something went wrong but complete
failure();
}
};
this.xhr.open(method, url, true);
this.xhr.send();
}
};
Ajax.request(url, "GET", null, function(data) {
console.log("success");
}, function() {
console.log("failed");
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment