Created
June 28, 2018 13:19
-
-
Save hugofabricio/380571f0fa3626199181da90fd939437 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
class Send { | |
constructor() { | |
console.log('>>> Send constructor'); | |
let forms = document.getElementsByClassName('js-send-form'); | |
Array.from(forms).forEach((form) => { | |
form.addEventListener('submit', (evt) => { | |
evt.preventDefault(); | |
this.handleOnSubmit(form, evt); | |
}); | |
}); | |
} | |
handleOnSubmit(form, evt) { | |
const that = this; | |
let headers = new Headers(), | |
formData = new FormData(); | |
headers.set('Accept', 'application/json'); | |
for (let i = 0; i < form.length; ++i) { | |
formData.append(form[i].name, form[i].value); | |
} | |
fetch(form.action, { | |
method: 'POST', | |
credentials: 'same-origin', | |
headers, | |
body: formData | |
}) | |
.then(response => { | |
return response.json(); | |
}) | |
.then(data => { | |
if (data.success === false) throw data.errors; | |
return data; | |
}) | |
.then(success => { | |
that.removeClasses(form); | |
}) | |
.catch(errors => { | |
that.removeClasses(form); | |
for (let key in errors) { | |
let input = form.querySelector(`[name^=${key}`); | |
let group = input.closest('.form-group'); | |
group.classList.add('-wrong'); | |
group.querySelector('.help-block').innerHTML = errors[key]; | |
} | |
}); | |
} | |
removeClasses(form) { | |
let groups = form.querySelectorAll('.form-group'); | |
Array.from(groups).forEach((group) => { | |
if (group.classList.contains('-wrong')) group.classList.remove('-wrong'); | |
group.querySelector('.help-block').innerHTML = ''; | |
}); | |
} | |
} | |
export default Send; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment