Skip to content

Instantly share code, notes, and snippets.

@ShivrajRath
Last active August 29, 2015 13:55
Show Gist options
  • Save ShivrajRath/8746229 to your computer and use it in GitHub Desktop.
Save ShivrajRath/8746229 to your computer and use it in GitHub Desktop.
Ajax Caller
var appCaller = {
/**
* Handler for all async application calls
* @param {[Object]} ajaxSetupJSON [This is passed to $.ajaxSetup()],
* URL and data are expected to be sent
* @param {[function]} successCallback [function to be called on success response]
* @param {[function]} errorCallback [function to be called on error response]
* @param {[function]} completeCallBack [function to be called on response completion, it's OPTIONAL]
* @return {[function]} [based on error]
*/
callAsync: function (ajaxSetupJSON, successCallback, errorCallback, completeCallBack) {
ajaxSetupJSON.async = true;
this.defaultAjaxSetup(ajaxSetupJSON);
return $.ajax(ajaxSetupJSON)
.done(function (data, textStatus, jqXHR) {
if (successCallback) {
successCallback(data, textStatus, jqXHR);
}
})
.fail(function (jqXHR, textStatus, errorThrown) {
if (errorCallback) {
errorCallback(jqXHR, textStatus, errorThrown);
}
})
.always(function () {
if (completeCallBack) {
completeCallBack();
}
});
},
/**
* Handler for all async application calls
* @param {[Object]} ajaxSetupJSON [This is passed to $.ajaxSetup()],
* @return {[responseObject]} [response from success/error]
*/
callSync: function (ajaxSetupJSON, successCallback, errorCallback, completeCallBack) {
ajaxSetupJSON.async = false;
this.defaultAjaxSetup(ajaxSetupJSON);
var resp = "";
$.ajax(ajaxSetupJSON)
.done(function (data, textStatus, jqXHR) {
if (successCallback) {
successCallback(data, textStatus, jqXHR);
}
resp = data;
})
.fail(function (jqXHR, textStatus, errorThrown) {
if (errorCallback) {
errorCallback(jqXHR, textStatus, errorThrown);
}
resp = jqXHR;
})
.always(function () {
if (completeCallBack) {
completeCallBack();
}
});
return resp;
},
/**
* Gives a default configuration to request object
*/
defaultAjaxSetup: function (ajaxJSON) {
if (!ajaxJSON.cache) ajaxJSON.cache = false;
if (!ajaxJSON.type) ajaxJSON.type = 'POST';
if (!ajaxJSON.dataType) ajaxJSON.dataType = 'json';
if (!ajaxJSON.contentType) ajaxJSON.contentType = 'application/json; charset=utf-8';
if (!ajaxJSON.timeout) ajaxJSON.timeout = 600000;
if (!ajaxJSON.headers) ajaxJSON.headers = {
'cache-control': 'no-cache'
};
}
};
@ShivrajRath
Copy link
Author

Removing $.ajaxSetup, it would have run into issues if ran multiple times.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment