Skip to content

Instantly share code, notes, and snippets.

@th3hunt
Last active October 1, 2020 10:55
Show Gist options
  • Save th3hunt/3fae9a4b2edc9d74274c to your computer and use it in GitHub Desktop.
Save th3hunt/3fae9a4b2edc9d74274c to your computer and use it in GitHub Desktop.
Global ajax handling skeleton
(function (App) {
/**
* Do before each Ajax request
* ---------------------------
*
* 1. Disable ajax related DOM controls to prevent double submissions
* 2. Extend each XHR object with a couple of methods that let ajax calls skip global handlers on-demand.
*
*/
$(document).ajaxSend(function (event, xhr, settings) {
xhr.skipGlobalHandlers = function () {
xhr._skipGlobalHandlers = true;
};
xhr.shouldSkipGlobalHandlers = function () {
return xhr._skipGlobalHandlers === true;
};
if (App.session.id) {
xhr.setRequestHeader("X-User-Id", App.session.id);
}
try {
// do other stuff
} catch (e) {
return false;
}
});
/**
* After each ajax request
* -----------------------
*
*/
$(document).ajaxComplete(function (event, xhr, settings) {
});
function handleSessionTimeout () {
App.showModal(new App.shared.views.SessionTimeout());
}
function handleAccountDeactivation () {
App.showModal(new App.shared.views.AccountDeactivation({ message: message }));
}
/**
* Global ajax error handler
* -------------------------
*
* Individual ajax calls can skip global handling either
* using global: false option beforehand, or dynamically after receiving the response
* by calling #skipGlobalHandlers on the XHR object.
*
*/
$(document).ajaxError(function (event, xhr, ajaxSettings, thrownError) {
if (xhr.shouldSkipGlobalHandlers() || _.contains(["abort"], (thrownError || "").toLowerCase())) {
return;
}
switch (xhr.status) {
case 401: // unauthenticated
if (xhr.responseText.search('deactivated') > -1) {
App._handleAccountDeactivation(xhr.responseText);
}
else {
App._handleSessionTimeout();
}
break;
case 403: // forbidden
feedback.warn("You are not authorized to perform the requested operation.");
break;
case 422: // validation errors
break;
case 409:
feedback.error(xhr.responseJSON.error);
break;
case 427: // stale or invalid csrf token, same user
feedback.error("This operation was not available at this time. Please try again.");
utils.acquireCSRFToken();
break;
case 428: // stale or invalid csrf token, other user
location.href = "/";
break;
default:
feedback.error("We could not perform your request at this time due to an unexpected error.");
}
});
}(MyApp));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment