Skip to content

Commit 2281479

Browse files
committed
Update application.js
- Use native fetch and remove ajax:success - dont rely on rails ujs related to #5465
1 parent e4ec6f6 commit 2281479

1 file changed

Lines changed: 42 additions & 3 deletions

File tree

app/assets/javascripts/application.js

Lines changed: 42 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -22,8 +22,47 @@
2222

2323
// Wait for the modal to open
2424
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+
});
2867
});
2968
});

0 commit comments

Comments
 (0)