Skip to content

Instantly share code, notes, and snippets.

@hvitorino
Created January 29, 2013 19:57
Show Gist options
  • Select an option

  • Save hvitorino/4667198 to your computer and use it in GitHub Desktop.

Select an option

Save hvitorino/4667198 to your computer and use it in GitHub Desktop.
(function (n) {
n.Ajax = n.Ajax || {};
n.Ajax.Request = function () {
this.url = "/";
this.requestDataType = "application/json";
this.responseDataType = "application/json";
this.successCallback = null;
this.internalErrorCallback = null;
this.notFoundCallback = null;
this.badRequestCallback = null;
this.for = function (url) {
this.url = url;
return this;
};
this.onSuccess = function (callback) {
this.successCallback = callback;
return this;
};
this.onInternalError = function (callback) {
this.internalErrorCallback = callback;
return this;
};
this.onNotFound = function (callback) {
this.notFoundCallback = callback;
return this;
};
this.onBadRequest = function (callback) {
this.badRequestCallback = callback;
return this;
};
this.sending = function (mime) {
this.requestDataType = mime;
return this;
};
this.sendingJson = function () {
this.requestDataType = "application/json";
return this;
};
this.expecting = function (mime) {
this.requestDataType = mime;
return this;
};
this.expectingHtml = function () {
this.requestDataType = "text/html";
return this;
};
this.expectingJson = function () {
this.responseDataType = "json";
return this;
};
this.run = function (httpMethod, data) {
var doNothing = function () {
};
$.ajax({
url: this.url,
type: httpMethod,
contentType: this.requestDataType,
data: data,
dataType: this.responseDataType,
success: this.successCallback,
statusCode: {
400: this.badRequestCallback || doNothing,
404: this.notFoundCallback || doNothing,
500: this.internalErrorCallback || doNothing
}
});
};
this.get = function (data) {
this.run("GET", data);
};
this.post = function (data) {
this.run("POST", data);
};
};
}(nlib));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment