Skip to content

Instantly share code, notes, and snippets.

@kuncevic
Created March 12, 2018 08:57
Show Gist options
  • Select an option

  • Save kuncevic/68365933331da0d076e0d95438def4d9 to your computer and use it in GitHub Desktop.

Select an option

Save kuncevic/68365933331da0d076e0d95438def4d9 to your computer and use it in GitHub Desktop.
jQuery API Call Utility
var Service = (function () {
Service.prototype.Call = function (input) {
var output = new dataOut(42);
if (!input.url) output.status = "url is undefined";
if (!input.data) output.status = "data is undefined";
if (output.status != 42)
return output;
//defaults:
if (!input.type) input.type = "POST";
if (!input.contentType) input.contentType = "application/json";
if (!input.dataType) input.dataType = "json";
//example:
//type: 'POST',
//url: '/home/DeleteBoardItem',
//data: JSON.stringify(itemData),
//contentType: "application/json",
//dataType: 'json'
$.ajax({
type: input.type,
url: input.url,
data: JSON.stringify(input.data),
contentType: input.contentType,
dataType: input.dataType
}).done(function (data) {
output.data = data;
output.status = 200;
input.callBackAction(output)
}).fail(function (jqXHR, textStatus, errorThrown) {
output.status = textStatus;
output.exeption = errorThrown;
input.callBackAction(output)
});
}
});
function ServiceOut(status, exeption, data) {
this.status = status;
this.exeption = exeption;
this.data = data
}
function SerivceIn(url, data, callBackAction, type, contentType, dataType) {
this.url = url;
this.data = data;
this.type = type;
this.contentType = contentType;
this.dataType = dataType;
this.callBackAction = callBackAction;
}
// use case:
var BoardService = (function () {
BoardService.prototype.service = new Service();
BoardService.prototype.DeleteBoard = function (data) {
var input = new ServiceIn("/home/DeleteBoard", data, this._callback_BoardDeleted);
var service = new Service().Call(input);
}
this._callback_BoardDeleted = function (output) {
if (output.status == 200) {
location.reload();
}
else if (output.status == 42) {
alert("Board remove error");
}
else {
alert("Uknown error");
}
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment