|
22 | 22 |
|
23 | 23 | // Wait for the modal to open |
24 | 24 | document.addEventListener('show.blacklight.blacklight-modal', function () { |
25 | | - // Wait for the form to be submitted successfully |
26 | | - $('.modal_form').on('ajax:success', function () { |
27 | | - Blacklight.Modal.hide(); |
| 25 | + // Attach a vanilla submit handler to modal forms that submits via fetch |
| 26 | + // and hides the Blacklight modal on a successful response. We mark forms |
| 27 | + // that we've attached to so we don't double-bind when the modal reopens. |
| 28 | + document.querySelectorAll('.modal_form').forEach(function (form) { |
| 29 | + if (form.dataset.vanillaHandlerAdded) return; |
| 30 | + form.dataset.vanillaHandlerAdded = 'true'; |
| 31 | + |
| 32 | + form.addEventListener('submit', function (e) { |
| 33 | + e.preventDefault(); |
| 34 | + |
| 35 | + var action = form.getAttribute('action') || window.location.href; |
| 36 | + var method = (form.getAttribute('method') || 'GET').toUpperCase(); |
| 37 | + var fetchOptions = { method: method, credentials: 'same-origin' }; |
| 38 | + |
| 39 | + var formData = new FormData(form); |
| 40 | + |
| 41 | + if (method === 'GET') { |
| 42 | + // Append form data to query string for GET |
| 43 | + var params = new URLSearchParams(formData); |
| 44 | + action += (action.indexOf('?') === -1 ? '?' : '&') + params.toString(); |
| 45 | + } else { |
| 46 | + fetchOptions.body = formData; |
| 47 | + } |
| 48 | + |
| 49 | + fetch(action, fetchOptions) |
| 50 | + .then(function (response) { |
| 51 | + if (response.ok) { |
| 52 | + Blacklight.Modal.hide(); |
| 53 | + } else { |
| 54 | + return response.text().then(function (body) { |
| 55 | + console.error( |
| 56 | + 'Modal form submission failed', |
| 57 | + response.status, |
| 58 | + body |
| 59 | + ); |
| 60 | + }); |
| 61 | + } |
| 62 | + }) |
| 63 | + .catch(function (err) { |
| 64 | + console.error('Modal form submission error', err); |
| 65 | + }); |
| 66 | + }); |
28 | 67 | }); |
29 | 68 | }); |
0 commit comments