Skip to content

Instantly share code, notes, and snippets.

@roperzh
Created July 14, 2014 02:37
Show Gist options
  • Save roperzh/ecbbaf64d60030f73c99 to your computer and use it in GitHub Desktop.
Save roperzh/ecbbaf64d60030f73c99 to your computer and use it in GitHub Desktop.
Simple ajax service, IE9+ compatible
// -------------------------------------------
// Ajax Stuff
// -------------------------------------------
Ajax = {
get: function(options) {
options.method = "GET";
this.request(options);
},
delete: function(options) {
options.method = "DELETE";
this.request(options);
},
post: function(options) {
options.method = "POST";
options = this.prepareForPostOrPut(options);
this.request(options);
},
put: function(options) {
options.method = "PUT";
options = this.prepareForPostOrPut(options);
this.request(options);
},
request: function(options) {
var request = new XMLHttpRequest();
request.open(options.method, options.url);
this.setHeaders(request, options.headers);
this.setCallbacks(request, options);
request.send(options.data);
},
setHeaders: function(request, headers) {
for(var headerName in headers) {
request.setRequestHeader(headerName, headers[headerName]);
}
},
setCallbacks: function(request, options) {
request.onload = function() {
if (request.status >= 200 && request.status < 400) {
options.success(request);task
} else {
options.error(request);
}
};
request.onerror = function() {
options.error(request);
};
},
prepareForPostOrPut: function(options) {
/* If the data isn't a FormData object, lets encode it */
if(!options.data.toString().match("FormData")) {
options.headers = options.headers || {};
options.headers['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8';
options.data = formurlencoded.encode(options.data);
}
return options;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment