diff --git a/app/javascript/shared/rails-ujs-fix.js b/app/javascript/shared/rails-ujs-fix.js index 19aac8054..a7cc7eb5e 100644 --- a/app/javascript/shared/rails-ujs-fix.js +++ b/app/javascript/shared/rails-ujs-fix.js @@ -24,3 +24,22 @@ addEventListener('load', () => { return element.href || href(element); }; }); + +// rails-ujs installs CSRFProtection for its own ajax implementation. We might need +// CSRFProtection for jQuery initiated requests. This code is from jquery-ujs. +jQuery.ajaxPrefilter((options, originalOptions, xhr) => { + if (!options.crossDomain) { + CSRFProtection(xhr); + } +}); + +function csrfToken() { + return jQuery('meta[name=csrf-token]').attr('content'); +} + +function CSRFProtection(xhr) { + let token = csrfToken(); + if (token) { + xhr.setRequestHeader('X-CSRF-Token', token); + } +}