Answer the question
In order to leave comments, you need to log in
How to pass parent to onclick?
Hello. There is this form:
<form enctype="multipart/form-data" method="post" id="formFiz1" php="mainfizcheck.php">
<p>Фамилия Имя Отчество</p>
<input name="formFIO" type="text">
<p>Дата рождения</p>
<input name="formBday" type="text" >
<input value="Отправить" type="submit" class="btnForm" onclick="submitHandler(event, '#formFiz1')">
</form>
let sendBtn = document.querySelectorAll(".btnForm");
function submitHandler(event, nameform){
event.preventDefault();
form = document.querySelector(nameform);
fetch(form.getAttribute("php"), {
method: "POST",
body: new FormData(form)
})
.then(response => response.json())
.then(function(json) { console.log(json); })
.catch(function(error) { console.log(error); });
}
Answer the question
In order to leave comments, you need to log in
And why not hang up the handler on the form submission? Why the button? Well, your php attribute is called action by normal boys))
How to pass parent to onclick?
Is there any more elegant way than mine?
class FormSubmitHandler{
constructor(form){
this.form = form;
this.isSending = false;
this.form.addEventListener('submit', this.onSubmit.bind(this));
}
onSubmit(e){
e.preventDefault();
// не отправляем форму пока ответ не пришел
if(this.isSending)
return;
const data = new FormData(this.form);
if(!this.validate(data))
return;
this.isSending = true;
this.send(this.form.getAttribute("php"), data);
}
send(url, data){
fetch(url, {
method: "POST",
body: data,
})
.then(response => response.json())
.then(this.onCommit.bind(this))
.catch(this.onBadRequest.bind(this));
}
onCommit(responseData){
console.log(responseData, this.form);
this.isSending = false;
}
onBadRequest(error){
console.log(error, this.form);
this.isSending = false;
}
validate(data){
console.log(data.getAll(), this.form);
// проверка полей формы
}
}
///////////////////////////////////////////////
document.querySelectorAll('form').forEach((formElm) => {
new FormSubmitHandler(formElm);
});
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question