For those encountering a similar issue as I did with my page redirecting to a JSON response after form submission, here's how I resolved it:
import { ref, onMounted, nextTick } from 'vue'
onMounted(() => {
nextTick(() => {
form.value.addEventListener('submit', handleFormSubmit)
})
})
function handleFormSubmit(event) {
event.preventDefault()
const formData = getFormData(form.value)
const data = formData.data
// Check for spam bot honeypot field
if (formData.honeypot) {
return false
}
disableAllButtons(form.value)
const url =
'https://script.google.com/macros/s/AKfycbzuG3ea4BPkC27joSKGPmDTxtNqvP5cyXiNjeC_IRfpLhsyxmM7DMbxLvtUmfPxWmJw_A/exec'
const xhr = new XMLHttpRequest()
xhr.open('POST', url)
xhr.setRequestHeader('content-Type', 'application/x-www-form-urlencoded')
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
form.value.reset()
const formElements = form.value.querySelector('.form__elements')
if (formElements) {
formElements.style.display = 'none' //hide form
}
const thankYouMessage = form.value.querySelector('.thankyou_message')
if (thankYouMessage) {
thankYouMessage.style.display = 'block'
}
sending.value = false
showSuccessModal.value = true // show success modal
window.location.reload() // reload the page
}
}
//url encode form data before sending as post data
const encoded = Object.keys(data)
.map(function (k) {
return encodeURIComponent(k) + '=' + encodeURIComponent(data[k])
})
.join('&')
xhr.send(encoded)
}
function getFormData(form) {
const elements = form.elements
const data = {}
for (let i = 0; i < elements.length; i++) {
let element = elements[i]
let name = element.name
let value = element.value
if (name) {
data[name] = value
}
}
return { data: data }
}
function disableAllButtons(form) {
const buttons = form.querySelectorAll('button')
for (let i = 0; i < buttons.length; i++) {
buttons[i].disabled = true
}
}
Upon submitting the form, a confirmation modal appears and the page reloads to enable the form again for future submissions.