-
-
Save ryanirelan/a6cb74c6c4dd4fd674a7f2a587dbd8d4 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(function () { | |
const form = document.querySelector('form'); | |
const spinner = document.getElementById("processingIndicator"); | |
const button = document.querySelector("button"); | |
const successAlert = document.getElementById("successAlert"); | |
const errorAlert = document.getElementById("errorAlert"); | |
const query = `mutation saveContactForm($firstName: String, $lastName: String, $company: String, $phoneNumber: String, $email: String, $message: String, $authorId: ID) { save_submissions_contactForm_Entry(firstName: $firstName, lastName: $lastName, company: $company, phoneNumber: $phoneNumber, email: $email, message: $message, authorId: $authorId) { firstName lastName company phoneNumber email message }}` | |
var processingFormState = function() | |
{ | |
button.disabled = true; | |
spinner.classList.remove('hidden'); | |
} | |
var prepFormData = function(target) | |
{ | |
const formData = new FormData(target); | |
return { | |
query: `${query}`, | |
variables: { | |
firstName: formData.get('firstName'), | |
lastName: formData.get('lastName'), | |
company: formData.get('company'), | |
phoneNumber: formData.get('phoneNumber'), | |
email: formData.get('email'), | |
message: formData.get('message'), | |
authorId: 1 | |
} | |
} | |
} | |
var afterProcessingFormState = function(target, status) | |
{ | |
spinner.classList.add('hidden'); | |
if (status === 'success') { | |
target.reset() | |
successAlert.classList.remove('hidden'); | |
} else { | |
errorAlert.classList.remove('hidden'); | |
} | |
document.querySelector("button").disabled = false | |
} | |
var handleFormSubmission = function(event) | |
{ | |
event.preventDefault(); | |
processingFormState(); | |
let body = prepFormData(event.target); | |
let url = window.graphqlEndpoint; | |
let opts = { | |
method: 'POST', | |
headers: { | |
"Content-Type": "application/json", | |
"Authorization": `Bearer ${window.graphqlToken}`, | |
}, | |
body: JSON.stringify(prepFormData(event.target)) | |
} | |
fetch(url, opts) | |
.then(response => response.json()) | |
.then(response => { | |
if (response.errors) { | |
afterProcessingFormState(event.target, 'error') | |
console.log(response) | |
} else { | |
afterProcessingFormState(event.target, 'success') | |
} | |
}) | |
.catch(error => { | |
afterProcessingFormState(event.target, 'error') | |
console.log(error) | |
}) | |
} | |
form.addEventListener('submit', handleFormSubmission ) | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment