
FetchIt
Lightweight AJAX form submission in MODX via the Fetch API on top of FormIt or a custom snippet


Use cases with Bootstrap Modal.
Form inside a modal. Listen for fetchit:success.
If you created the modal in JS:
const exampleModal = new bootstrap.Modal(document.getElementById('exampleModal'))
document.addEventListener('fetchit:success', () => {
exampleModal.hide()
})If the modal opens via Bootstrap data attributes:
document.addEventListener('fetchit:success', ({ detail: { form } }) => {
const modal = form.closest('.modal')
const modalInstance = bootstrap.Modal.getInstance(modal)
if (!modalInstance) {
return
}
modalInstance.hide()
})Внимание
In Bootstrap 5.3, bootstrap.Modal.getInstance() sometimes returns null for modals opened only via the data API. Workaround below.
document.addEventListener('fetchit:success', ({ detail: { form } }) => {
const modal = form.closest('.modal')
if (!modal) {
return
}
const closeBtn = modal.querySelector('[data-bs-dismiss="modal"]')
if (!closeBtn) {
return
}
closeBtn.click()
})Show the modal and insert message from the response:
document.addEventListener('fetchit:success', ({ detail: { response: { message } } }) => {
const modal = bootstrap.Modal.getOrCreateInstance('#exampleModal')
const body = modal._element.querySelector('.modal-body')
body.textContent = message
modal.show()
})textContent is safer than innerHTML: the server message may contain markup, and sanitizeHTML is not called here.