My form button needs to be clicked twice for the form to show error / success message.

huangapple go评论52阅读模式
英文:

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

主要JS文件

感谢您的每一点帮助。

提交函数

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

main JS file

Appreciate every little help.

Submit Function

function submitForm() {
if (nameInputValidation &amp;&amp; emailInputValidation &amp;&amp; numberOfPeopleValidation &amp;&amp; phoneInputValidation &amp;&amp; isChecked &amp;&amp; foundAboutUsValidation) {
submissionAlert.classList.add(&quot;show&quot;);
successMessage.classList.add(&quot;show&quot;);
const scriptURL = &quot;[GOOGLE-SCRIPT]&quot;;
fetch(scriptURL, { method: &quot;POST&quot;, body: new FormData(form) })
.then(successMessage.classList.add(&quot;show&quot;))
.catch(errorMessage.classList.add(&quot;show&quot;));
// Send data to PHP script with AJAX request
var xhr = new XMLHttpRequest();
xhr.open(&quot;POST&quot;, &quot;./phpmailer/index.php&quot;, true);
xhr.setRequestHeader(&quot;Content-type&quot;, &quot;application/x-www-form-urlencoded&quot;);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 &amp;&amp; xhr.status == 200) {
successMessage.classList.add(&quot;.show&quot;);
} else {
errorMessage.classList.add(&quot;.show&quot;);
}
};
// Get form data
var name = document.getElementById(&quot;name&quot;).value;
var email = document.getElementById(&quot;email&quot;).value;
var message = document.getElementById(&quot;message&quot;).value;
var dateFor = document.getElementById(&quot;date-for&quot;).value;
var phoneNumber = document.getElementById(&quot;phoneNumber&quot;).value;
var numberOfPeople = document.getElementById(&quot;numberOfPeople&quot;).value;
var foundAboutUs = document.getElementById(&quot;foundAboutUs&quot;).value;
xhr.send(
&quot;name=&quot; +
name +
&quot;&amp;email=&quot; +
email +
&quot;&amp;message=&quot; +
message +
&quot;&amp;phoneNumber=&quot; +
phoneNumber +
&quot;&amp;date-for=&quot; +
dateFor +
&quot;&amp;numberOfPeople=&quot; +
numberOfPeople +
&quot;&amp;foundAboutUs=&quot; +
foundAboutUs
);
phoneInput.parentElement.style.display = &quot;none&quot;;
} else {
checkInputs();
}
}

HTML Form without unnecessary inputs

&lt;form name=&quot;contact-form&quot; class=&quot;contact&quot; id=&quot;contact-form&quot; onsubmit=&quot;event.preventDefault(); submitForm();&quot;&gt;
&lt;div class=&quot;form-group&quot;&gt;
&lt;button type=&quot;submit&quot; name=&quot;submit&quot; value=&quot;Send Message&quot; class=&quot;btn btn-primary&quot; id=&quot;submit-btn&quot;&gt;Submit&lt;/button&gt;
&lt;/div&gt;
&lt;/form&gt; 

I have tried many different things such as

-> Putting onSubmit=&quot;event.preventDefault(); submitForm();&quot; on form
-> putting onClick=&quot;onSubmit(&#39;event)&quot; 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: &quot;POST&quot;, body: new FormData(form) })
.then(successMessage.classList.add(&quot;show&quot;))
.catch(errorMessage.classList.add(&quot;show&quot;));

Here is how you should implement fetch:

fetch(scriptURL, { method: &quot;POST&quot;, body: new FormData(form) })
.then(response =&gt; {
if(response.ok) {
successMessage.classList.add(&quot;show&quot;);
} else {
throw new Error(&#39;Form submission failed&#39;);
}
})
.catch(error =&gt; {
errorMessage.classList.add(&quot;show&quot;);
});

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(&quot;.show&quot;);
errorMessage.classList.add(&quot;.show&quot;);

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(&quot;POST&quot;, &quot;./phpmailer/index.php&quot;, true);
xhr.setRequestHeader(&quot;Content-type&quot;, &quot;application/x-www-form-urlencoded&quot;);
xhr.onreadystatechange = function () {...};

to this

xhr.onreadystatechange = function () {...};
xhr.open(&quot;POST&quot;, &quot;./phpmailer/index.php&quot;, true);
xhr.setRequestHeader(&quot;Content-type&quot;, &quot;application/x-www-form-urlencoded&quot;);

See if these changes can solve your issue.

huangapple
  • 本文由 发表于 2023年6月29日 20:02:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/76580868.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定