Skip to content

Instantly share code, notes, and snippets.

@ivanaugustobd
Last active January 7, 2019 10:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ivanaugustobd/eab46bcbbb60f356d6f26a481b891274 to your computer and use it in GitHub Desktop.
Save ivanaugustobd/eab46bcbbb60f356d6f26a481b891274 to your computer and use it in GitHub Desktop.
const submitForm = form => {
// se quiser colocar um efeito de loading, ele vai aqui
const previousMessage = form.querySelector('.message')
if (previousMessage) {
form.removeChild(previousMessage) // remove a mensagem de algum submit anterior
}
const body = new FormData(form) // coloca os inputs/select/textarea do form numa variável
const method = form.method // pega o método do form (GET/POST)
// envia o form pra sua respectiva action
fetch(form.action, {method, body}).then(response => { // e quando tiver terminado..
const message = document.createElement('span') // cria o elemento que será usado pra exibir a mensagem retornada
message.classList.add('message') // vamos colocar uma classe pra poder identificá-lo posteriormente
message.innerText = response // colocamos a resposta do backend/API nele
form.appendChild(message) // mandamos colocar a mensagem no fim do form
// se tiver colocado um efeito de loading, remova-o aqui
})
return false
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment