连接java脚本和PHP的问题

问题描述 投票:0回答:1

我对 PHP 的了解非常少。我有一个 html 表单。当表单提交时,它应该向特定邮箱发送一封电子邮件。当表单无效时,我在 JS 中定义了错误。我正在使用 php mailer 进行表单提交。我面临的问题是,当我从 html 中删除 js 文件时,邮件已发送(错误未显示),而当我将其放回时,邮件未发送。我不知道如何连接这三个文件,因此当输入为空时会出现错误,而当表单有效时会收到一封邮件。在 PHP 文件中,我在邮件中使用 $$$ 来隐藏真实信息。

   <form action="./send-mail.php" method="post">
            <div class="b-form__inputWrap">
                <label for="name">Name</label>
                <input name="name" id="name">
                <div class="error hidden">Please enter name</div>
            </div>

            <div class="b-form__inputWrap">
                <label for="email">Email</label>
                <input name="email" id="email">
                <div class="error hidden">Please enter email</div>
            </div>

            <div class="b-form__inputWrap">
                <label for="text">Phone</label>
                <input name="phone" id="phone" placeholder="+">
                <div class="error hidden">Please enter phone number</div>
            </div>

            <div class="b-form__inputWrap">
                <label for="subject">Subject</label>
                <input name="subject" id="subject">
            </div>

            <div class="b-form__inputWrap">
                <label for="message">Message</label>
                <textarea name="message" id="message" name="message"></textarea>
                <div class="error hidden">Please enter message</div>
            </div>

            <button class="b-form__btn" type="submit" name="submit">Send</button>
        </form>

JAVA脚本

        const form = document.querySelector('form');
        const firstName = document.getElementById('name');
        const email = document.getElementById('email');
        const phone = document.getElementById('phone');
        const textMessage = document.getElementById('message');

       const error = document.querySelectorAll('.error');
       const errorOther = document.querySelector('.errorOther');
       const message = document.querySelector('.b-form__message');

      let validationOn = false;
      let formValid = false;

        const isValidEmail = () =>{
         const patern= /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0- 
         9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
         return String(email.value).toLowerCase().match(patern);
         }

       const isValidPhone = () =>{
        const patern = /^[\+]?[(]?[0-9]{3}[)]?[-\s\.]?[0-9]{3}[-\s\.]?[0-9]{4,6}$/im;
         return String(phone.value).toLowerCase().match(patern);
         }

         const displayErrors = (el) =>{
          el.nextElementSibling.classList.remove('hidden');
         el.classList.add('invalid');
         }

         const resetInput = (el) =>{
         el.nextElementSibling.classList.add('hidden');
         el.classList.remove('invalid');
          }

       const isValid = () =>{
       formValid = true;
       if(!validationOn) return;
       resetInput(firstName);
       resetInput(email);
       resetInput(phone);
       resetInput(textMessage);
 
       if(firstName.value === '' || firstName.value === null){
       displayErrors(firstName);
       formValid =false;
       }

       if(!isValidEmail(email.value)){
       displayErrors(email);
      formValid = false;
        }

      if(!isValidPhone(phone.value)){
      displayErrors(phone);
      formValid = false;
      }

if(textMessage.value === '' || textMessage.value === null){
    displayErrors(textMessage);
    formValid = false;
}
}

     const inputs = [firstName,email,phone,textMessage];


     form.addEventListener('submit', (e) => {
     e.preventDefault();
     validationOn = true;
     isValid();
     validationOn = false;

if (formValid) {
    const formData = new FormData(form);

    fetch('./send-mail.php', {
        method: 'POST',
        body: formData
    })
    .then(response => response.text())
    .then(data => {
        console.log('hello'); // Log the response from the server
        // Handle the response as needed
    })
    .catch(error => {
        console.error('Error:', error);
    });
    
    form.remove();
    message.classList.remove('hidden');
}
  });

    inputs.forEach((inp) =>{
     inp.addEventListener('input', ()=>{
     isValid();
     })
  })

PHP

    <?php

 error_reporting(E_ALL);
 ini_set('display_errors', 1); 

 use PHPMailer\PHPMailer\PHPMailer;
 use PHPMailer\PHPMailer\Exception;

require 'vendor/phpmailer/phpmailer/src/Exception.php';
require 'vendor/phpmailer/phpmailer/src/PHPMailer.php';
require 'vendor/phpmailer/phpmailer/src/SMTP.php';

 if (isset($_POST["submit"])) {
try {
    $mail = new PHPMailer(true);

    $mail->isSMTP();
    $mail->Host = 'smtp-relay.brevo.com'; // Use Sendinblue's SMTP server
    $mail->SMTPAuth = true;
    $mail->CharSet = 'UTF-8';
    $mail->Username = '$$$$$'; // Replace with your Sendinblue username
    $mail->Password = '$$$$$'; // Replace with your Sendinblue password
    $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS; // Use STARTTLS
    $mail->Port = 587;   

    // Set the sender's email address and name
    $mail->addAddress('$$$$$');
    $mail->setFrom($_POST['email']);
    $mail->addReplyTo($_POST['email']);
    
    $mail->isHTML(true);

    $mail->Subject = $_POST["subject"];
    $mail->Body = "This is the message from" . $_POST["message"];

    $mail->send();
    echo 'Email sent successfully!';
} catch (Exception $e) {
    echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
}
}

?>
javascript php phpmailer
1个回答
0
投票

• 检查 JavaScript 代码是否有任何可能阻止表单提交和电子邮件发送的错误或冲突 • 验证 PHP 代码是否存在与 PHPMailer 库和电子邮件发送过程相关的任何问题 • 确保 HTML 文件中的表单操作正确指向 PHP 文件进行处理

© www.soinside.com 2019 - 2024. All rights reserved.