如何在javascript表单验证后调用php文件

pbwdgjma  于 2023-01-01  发布在  PHP
关注(0)|答案(1)|浏览(153)

我正在做我的投资组合网站的联系形式。我工作的PHP形式,也工作JavaScript验证,但当我试图添加一个接一个的工作崩溃。

总结一下,我想知道如何在所有输入都有效后调用contactForm.php。

下面是我的JS代码:

function formValidator(){
          const form = document.getElementById('form');
          const name = document.getElementById('name');
          const email = document.getElementById('email');
          const message = document.getElementById('message');
          let errorStatus = true;
        
          form.addEventListener('submit',(e) => {
            e.preventDefault(); // here I stop submiting
            checkInputs(); // here I check validation of inputs
            if(errorStatus == true){ //if its ok I run this
    
              console.log("Its ok")
              var xhttp = new XMLHttpRequest();
              xhttp.onreadystatechange = function() 
              {
                  if (xhttp.readyState == 4 && xhttp.status == 200) {
                          document.getElementById("result").innerHTML = xhttp.responseText;}
              };
              xhttp.open("POST", "contactForm.php", true);
              xhttp.send();
            } 
    
    else{
            form.scrollIntoView({ behavior: 'smooth'});
            }
          });
        
          function checkInputs(){
            const nameValue = name.value.trim();
            const emailValue = email.value.trim();
            const messageValue = message.value.trim();
        
            if(nameValue === ''){
              setErrorFor(name, "Proszę podać imię");
        
            } else{
              setSuccessFor(name);
            }
          }
        
          function setErrorFor(input, message){
            const formControl = input.parentElement;
            const errorContent = formControl.querySelector('.error-message');
            const alertVisibility = formControl.querySelector('.alert');
        
            errorContent.innerText = message;
            alertVisibility.style.visibility = "visible";
        
            errorStatus = false;
          }
        
          function setSuccessFor(input){
            const formControl = input.parentElement;
            const alertVisibility = formControl.querySelector('.alert');
        
            alertVisibility.style.visibility = "hidden";
        
            errorStatus = true;
          }
        }

我添加了以下代码:

var xhttp = new XMLHttpRequest();
      xhttp.onreadystatechange = function() 
      {
          if (xhttp.readyState == 4 && xhttp.status == 200) {
                  document.getElementById("result").innerHTML = xhttp.responseText;}
      };
      xhttp.open("POST", "contactForm.php", true);
      xhttp.send();

这里是contactForm.php

<?php
// Get data from form 
$name = $_POST['name'];
$email= $_POST['email'];
$message= $_POST['message'];
 
$to = "piotr.brze95@gmail.com";
$subject = "Nowe zlecenie od " . $name . " z strony MelonStudio";
 
// The following text will be sent
// Name = user entered name
// Email = user entered email
// Message = user entered message
$txt ="Name = ". $name . "\r\n  Email = "
    . $email . "\r\n Message =" . $message;
 
$headers = "From: noreply@demosite.com";
if($email != NULL) {
    mail($to, $subject, $txt, $headers);
}
?>

我也做了一些研究来找到最好的方法来处理表单,这是我最后得到的. PHP表单和JS验证,但我不能把它们结合起来。
您也可以在此查看此网站:My Portfolio,联系表在页面末尾。

12月29日更新

经过一些代码更新,我设法发送电子邮件正确.
下面是我的JS代码,检查是否有错误,并获取php文件:

e.preventDefault();
        checkInputs();
    
        if(errorStatus === true){
          console.log("Its ok");
          phpFetcher();
          window.location.href = "https://melon.studio/success-page.html";
    
        } else{
        form.scrollIntoView({ behavior: 'smooth'});
        }
      });
    function phpFetcher(){
form.addEventListener('click', function(event){
    const formattedFormData = new FormData(form);
    postData(formattedFormData);
});

async function postData(formattedFormData){
    const response = await fetch('contactForm.php',{
        method: 'POST',
        body: formattedFormData
    });
}

问题是JS不会等待php文件的执行并立即重定向网站。

flvlnr44

flvlnr441#

header("Location:index.html");,这是第一个问题,你应该删除它,第二个问题是你没有发送 AJAX 调用的响应,你应该通过echo "Your message has been sent"发送ajax请求的响应,在你的情况下,你可以返回mail函数的结果,请在contactForm.php中添加此代码。

if(mail($to, $subject, $txt, $headers)) {
   echo "Your message has been sent";
} else {
   echo "Enter the valid email address"
}

相关问题