英文:
My form button needs to be clicked twice for the form to show error / success message
问题
我用HTML、CSS、JavaScript和php mailer作为后端制作了一个联系表单,它将表单信息发送到我的电子邮件和Google电子表格。
我的表单每次都能成功提交,但我需要点击两次提交按钮才能看到成功消息。
完整代码的Git存储库:
https://github.com/FranjoDumanovsky/Bar-crawl-zagreb
感谢您的每一点帮助。
提交函数
function submitForm() {
if (
nameInputValidation &&
emailInputValidation &&
numberOfPeopleValidation &&
phoneInputValidation &&
isChecked &&
foundAboutUsValidation
) {
submissionAlert.classList.add("show");
successMessage.classList.add("show");
const scriptURL = "[GOOGLE-SCRIPT]";
fetch(scriptURL, { method: "POST", body: new FormData(form) })
.then(successMessage.classList.add("show"))
.catch(errorMessage.classList.add("show"));
// 使用AJAX请求将数据发送到PHP脚本
var xhr = new XMLHttpRequest();
xhr.open("POST", "./phpmailer/index.php", true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
successMessage.classList.add("show");
} else {
errorMessage.classList.add("show");
}
};
// 获取表单数据
var name = document.getElementById("name").value;
var email = document.getElementById("email").value;
var message = document.getElementById("message").value;
var dateFor = document.getElementById("date-for").value;
var phoneNumber = document.getElementById("phoneNumber").value;
var numberOfPeople = document.getElementById("numberOfPeople").value;
var foundAboutUs = document.getElementById("foundAboutUs").value;
xhr.send(
"name=" +
name +
"&email=" +
email +
"&message=" +
message +
"&phoneNumber=" +
phoneNumber +
"&date-for=" +
dateFor +
"&numberOfPeople=" +
numberOfPeople +
"&foundAboutUs=" +
foundAboutUs
);
phoneInput.parentElement.style.display = "none";
} else {
checkInputs();
}
}
没有不必要输入的HTML表单
<form name="contact-form" class="contact" id="contact-form" onsubmit="event.preventDefault(); submitForm();">
<div class="form-group">
<button type="submit" name="submit" value="Send Message" class="btn btn-primary" id="submit-btn">Submit</button>
</div>
</form>
我尝试了许多不同的方法,例如
- 在表单上放置
onSubmit="event.preventDefault(); submitForm();"
- 在按钮元素上放置
onClick="onSubmit('event')"
,并在函数中使用event.preventDefault()
。 - 使用匿名函数处理提交代码的事件监听器
- 为按钮添加点击事件的事件监听器,或者为表单添加提交事件的事件监听器。
当我将其设置为一次点击时,错误和成功消息就不会显示,因为阻止默认行为似乎不起作用。如果没有刷新页面,必须点击两次按钮。
我尝试了一些StackOverflow答案,但没有成功。要么必须点击两次,要么阻止默认行为不起作用,页面在错误/成功消息之前就刷新了。
英文:
I made a contact form with html, css, JavaScript and with php mailer as backend that is sending form info to my e-mail and google spreadsheet.
My form submits successfully every time, but I need to click the submit button twice for the success message.
the Git repository with the full code:
https://github.com/FranjoDumanovsky/Bar-crawl-zagreb
Appreciate every little help.
Submit Function
function submitForm() {
if (nameInputValidation && emailInputValidation && numberOfPeopleValidation && phoneInputValidation && isChecked && foundAboutUsValidation) {
submissionAlert.classList.add("show");
successMessage.classList.add("show");
const scriptURL = "[GOOGLE-SCRIPT]";
fetch(scriptURL, { method: "POST", body: new FormData(form) })
.then(successMessage.classList.add("show"))
.catch(errorMessage.classList.add("show"));
// Send data to PHP script with AJAX request
var xhr = new XMLHttpRequest();
xhr.open("POST", "./phpmailer/index.php", true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
successMessage.classList.add(".show");
} else {
errorMessage.classList.add(".show");
}
};
// Get form data
var name = document.getElementById("name").value;
var email = document.getElementById("email").value;
var message = document.getElementById("message").value;
var dateFor = document.getElementById("date-for").value;
var phoneNumber = document.getElementById("phoneNumber").value;
var numberOfPeople = document.getElementById("numberOfPeople").value;
var foundAboutUs = document.getElementById("foundAboutUs").value;
xhr.send(
"name=" +
name +
"&email=" +
email +
"&message=" +
message +
"&phoneNumber=" +
phoneNumber +
"&date-for=" +
dateFor +
"&numberOfPeople=" +
numberOfPeople +
"&foundAboutUs=" +
foundAboutUs
);
phoneInput.parentElement.style.display = "none";
} else {
checkInputs();
}
}
HTML Form without unnecessary inputs
<form name="contact-form" class="contact" id="contact-form" onsubmit="event.preventDefault(); submitForm();">
<div class="form-group">
<button type="submit" name="submit" value="Send Message" class="btn btn-primary" id="submit-btn">Submit</button>
</div>
</form>
I have tried many different things such as
-> Putting onSubmit="event.preventDefault(); submitForm();"
on form
-> putting onClick="onSubmit('event)"
on button element, having event prevent default on function.
-> Event listener having anonymous function handling the submit code
->Event listener for button having Click event, or for Form having onSubmit event.
When I made it so it needs to be clicked once, the error & success messages wouldn't show because the prevent default wouldn't work i guess.
In case it didn't refresh the page, the button would have to be clicked twice
I tried using some stackOverflow anwsers, but I haven't had any luck with it. It either has to be clicked twice, or the preventDefault doesn't work and the page refreshes before error / success messages.
答案1
得分: 1
When I check your main JS file I see that you implemented the fetch() request wrong.
Here is your code on line 185:
fetch(scriptURL, { method: "POST", body: new FormData(form) })
.then(successMessage.classList.add("show"))
.catch(errorMessage.classList.add("show"));
Here is how you should implement fetch:
fetch(scriptURL, { method: "POST", body: new FormData(form) })
.then(response => {
if(response.ok) {
successMessage.classList.add("show");
} else {
throw new Error('Form submission failed');
}
})
.catch(error => {
errorMessage.classList.add("show");
});
with the event.preventDefault() function added to the top of your submitForm() function.
You've also wrongly implemented the classList.add() on line 195 and 197. Here is your code:
successMessage.classList.add(".show");
errorMessage.classList.add(".show");
Remove the dots before the "show".
Next, you've created an XMLHttpRequest and defined its onreadystatechange function. But you've done this after you've opened the request. The onreadystatechange function might not work as expected because of this. You should rearrange the order from this
xhr.open("POST", "./phpmailer/index.php", true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.onreadystatechange = function () {...};
to this
xhr.onreadystatechange = function () {...};
xhr.open("POST", "./phpmailer/index.php", true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
See if these changes can solve your issue.
英文:
When I check your main JS file I see that you implemented the fetch() request wrong.
Here is your code on line 185:
fetch(scriptURL, { method: "POST", body: new FormData(form) })
.then(successMessage.classList.add("show"))
.catch(errorMessage.classList.add("show"));
Here is how you should implement fetch:
fetch(scriptURL, { method: "POST", body: new FormData(form) })
.then(response => {
if(response.ok) {
successMessage.classList.add("show");
} else {
throw new Error('Form submission failed');
}
})
.catch(error => {
errorMessage.classList.add("show");
});
with the event.preventDefault() function added to the top of your submitForm() function.
You've also wrongly implemented the classList.add() on line 195 and 197. Here is your code:
successMessage.classList.add(".show");
errorMessage.classList.add(".show");
Remove the dots before the "show".
Next, you've created an XMLHttpRequest and defined its onreadystatechange function. But you've done this after you've opened the request. The onreadystatechange function might not work as expected because of this. You should rearrange the order from this
xhr.open("POST", "./phpmailer/index.php", true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.onreadystatechange = function () {...};
to this
xhr.onreadystatechange = function () {...};
xhr.open("POST", "./phpmailer/index.php", true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
See if these changes can solve your issue.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论