【问题标题】:Sending email in PHP using AJAX使用 AJAX 在 PHP 中发送电子邮件
【发布时间】:2018-10-09 17:23:18
【问题描述】:

我正在尝试使用 AJAX 在简单的联系表单中以 PHP 发送电子邮件。我有以下简单表单的代码、提交按钮的 PHP 代码和 AJAX 脚本。

当我尝试发送电子邮件时,它没有发送任何电子邮件并且总是触发 AJAX 错误消息。我不太擅长 AJAX 与 PHP 的集成。

下面是我的代码

 <form method="post" class="myform" action="">
       <input type="text" name="name" placeholder="Your Name" required><br>
       <input type="email" name="email" placeholder="Your Email" required><br>
       <textarea rows="4" cols="20" name="message" placeholder="Your Message"></textarea><br>
       <input type="submit" name="submit" value="Send"> <span class="output_message"></span>
 </form>

 <?php
     if (isset($_POST['submit'])) {
        $name = $_REQUEST['name'];
        $email = $_REQUEST['email'];
        $message = $_REQUEST['message'];

      // Set your email address where you want to receive emails. 
       $to = 'mymail@gmail.com';
       $subject = 'Contact Request From Website';
       $headers = "From: ".$name." <".$email."> \r\n";
       $send_email = mail($to,$subject,$message,$headers);

       echo ($send_email) ? 'success' : 'error';

  }?>

    <script>
           $(document).ready(function() {
           $('.myform').on('submit',function(){

           // Add text 'loading...' right after clicking on the submit button. 
           $('.output_message').text('Loading...'); 

           var form = $(this);
                $.ajax({
                url: form.attr('action'),
                method: form.attr('method'),
                data: form.serialize(),
                success: function(result){
            if (result == 'success'){
                $('.output_message').text('Message Sent!');  
            } else {
                $('.output_message').text('Error Sending email!');
            }
        }
    });

    // Prevents default submission of the form after clicking on the submit button. 
    return false;   
  });
  });

</script>

【问题讨论】:

  • 您遇到的错误是什么
  • 你的网址参数不为空吗?
  • 只有错误信息错误发送电子邮件
  • 在你的 $.ajax 代码中,你应该把 url: /path/to/your/phpfile.php
  • 但我没有外部php文件,只尝试将代码放在同一个文件中是不可能的?

标签: php ajax email


【解决方案1】:

所以,最佳答案有效,但正如@Mithu 所说,出于某种原因,它总是说: “发送电子邮件时出错!” 经过 30 分钟的探索,我了解到由于某种原因,它从 PHP 返回的不是“成功”而是“成功”,在“成功”或“错误”一词前面有 2-4 个空格。 所以,你只需要排除这些空格,因为我们需要将 'succes' 更改为 'this is success' 并将 'error' 更改为 'this is error' (只是为了在前面制作备用字母)然后我们需要将此字符串划分为单词并提取最后一个单词。无论脚本将添加多少空格或意外删除多少字母,它都将始终是“成功”或“错误”。而且您还需要在 PHP 中创建另一个 if else 语句来检查 FALSE 而不是 TRUE。

我还添加了几行来检查字段是否已填写。如果未填写,您会收到一条消息“请填写表格。”。

所以它的外观和工作方式对我来说是这样的:

导入jquery库(需要放到header中):

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

HTML(你需要把它放在你想要联系表格的地方):

<form method="post" class="myform" action="">
   <input type="text" name="name" placeholder="Your Name"><br>
   <input type="email" name="email" placeholder="Your Email"><br>
   <textarea rows="4" cols="20" name="message" placeholder="Your Message"></textarea><br>
   <input type="submit" name="submit" value="Send"> <span class="output_message"></span>
</form>

JS(需要放在页脚):

<script>
               $(document).ready(function() {
               $('.myform').on('submit',function(){
    
               // Add text 'loading...' right after clicking on the submit button. 
               $('.output_message').text('Loading...'); 
    
               var form = $(this);
                    $.ajax({
                    // if it can't find email.php just chahge the url path to the full path, including your domain and all folders.
                    url: "email.php",
                    method: form.attr('method'),
                    data: form.serialize(),
                    success: function(result){
                
                // THIS IS WHAT I HAVE ADDED TO REMOVE EXCESS SPACES
                let d = result.split(" ");
                let y = d.slice(-1)[0];
                // THIS IS WHAT I HAVE ADDED TO REMOVE EXCESS SPACES

                if (y == 'success'){
                    $('.output_message').text('Message Sent!');  
                } 
                else if (y == 'miss'){
                     $('.output_message').text('Please fill in all the fields above.');
                }
                else {
                    $('.output_message').text('Error Sending email!');
                }
            }
        });
    
        // Prevents default submission of the form after clicking on the submit button. 
        return false;   
      });
      });
    
</script>

email.php(您需要在您拥有 index.php 的同一文件夹中创建此文件):

 <?php


 // here we check if all fields are filled.
 $required = array('name', 'email', 'message');
 $error = false;
 foreach($required as $field) {
   if (empty($_REQUEST[$field])) {
     $error = true;
   }
 }

 //if something is not filled(empty) and error is true
 if ($error) {
   echo 'this is miss';
 }
 // if everything is filled then we execute the mail function
 else {

    $name = $_REQUEST['name'];
    $email = $_REQUEST['email'];
    $message = $_REQUEST['message'];

    $fullmessage = "Sender's name: ".$name."\n"."Message: \n".$message;

  // Set your email address where you want to receive emails.
   $to = 'contact@yourdomain.com';
   $subject = 'Message from YOUR E-MAIL.COM';
   $send_email = mail($to,$subject,$fullmessage,$email);


   if ($send_email == false) {
     echo 'this is error';
   } else {
     echo 'this is success';
   }
   }
   ?>

所以,这段代码对我来说稳定有效,但可能不是很专业,因为我是 JS 和 PHP 的初学者。

【讨论】:

  • 很好地阐明了失败的原因,并为其他开发人员提供了很好的代码示例。
  • @quinny,谢谢。我刚刚更新了它,因为我发现它并不总是在前面添加 3 个空格,但有时会添加 2 个或 1 个或什么都没有。所以,现在它必须是可靠的。
【解决方案2】:

您必须使用event.preventDefault(); 停止该表单的默认流程,并且可以将表单作为 multipart/formdata 或 form-data 传递并检查developer tools -&gt; network -&gt; fetch/xhr -&gt; payload/ formdata。然后您在 php 中创建一个单独的页面并在该页面中执行邮件处理并将表单操作链接更改为该页面

在 html 中

<form method="post" class="myform" action="mail.php">
   <input type="text" name="name" placeholder="Your Name"><br>
   <input type="email" name="email" placeholder="Your Email"><br>
   <textarea rows="4" cols="20" name="message" placeholder="Your Message"></textarea><br>
   <input type="submit" name="submit" value="Send"> <span class="output_message"></span>
</form>

<script>
         $(document).on('submit', '.myform', function(e){
              e.preventDefault();
           // Add text 'loading...' right after clicking on the submit button. 
           $('.output_message').text('Loading...'); 

           var form = $(this);
                $.ajax({
                url: form.attr('action'),
                method: form.attr('method'),
                data: new FormData($(".myform")[0]),
                dataType: 'json',
                processData: false,
                contentType: false,
                success: function(result){
            if (result.status == 'success'){
                $('.output_message').text('Message Sent!');  
            } else {
                $('.output_message').text('Error Sending email!');
            }
        }
    });
</script>

在 php - mail.php 中

if (isset($_POST['submit'])) {
        $name = $_REQUEST['name'];
        $email = $_REQUEST['email'];
        $message = $_REQUEST['message'];

      // Set your email address where you want to receive emails. 
       $to = 'mymail@gmail.com';
       $subject = 'Contact Request From Website';
       $headers = "From: ".$name." <".$email."> \r\n";
       $send_email = mail($to,$subject,$message,$headers);
       if($send_email)
        {
          $response = ['status' => 'success'];
        }
        else
        {
          $response = ['status' => 'error'];
        }
       echo json_encode($response);    
  }

【讨论】:

  • 请在您的答案中添加更多解释,以便其他人可以从中学习。比您早几个月的其他答案已经提到应该阻止表单提交(通过从该事件处理方法返回 false)
  • 对不起。我没有检查,我删除了它
【解决方案3】:

我会将 php 部分移动到另一个文件:

<form method="post" class="myform" action="">
       <input type="text" name="name" placeholder="Your Name" required><br>
       <input type="email" name="email" placeholder="Your Email" required><br>
       <textarea rows="4" cols="20" name="message" placeholder="Your Message"></textarea><br>
       <input type="submit" name="submit" value="Send"> <span class="output_message"></span>
 </form>



    <script>
           $(document).ready(function() {
           $('.myform').on('submit',function(){

           // Add text 'loading...' right after clicking on the submit button. 
           $('.output_message').text('Loading...'); 

           var form = $(this);
                $.ajax({
                url: "email.php",
                method: form.attr('method'),
                data: form.serialize(),
                success: function(result){
            if (result == 'success'){
                $('.output_message').text('Message Sent!');  
            } else {
                $('.output_message').text('Error Sending email!');
            }
        }
    });

    // Prevents default submission of the form after clicking on the submit button. 
    return false;   
  });
  });

</script>

在另一个 email.php 中

 <?php
     if (isset($_POST['submit'])) {
        $name = $_REQUEST['name'];
        $email = $_REQUEST['email'];
        $message = $_REQUEST['message'];

      // Set your email address where you want to receive emails. 
       $to = 'mymail@gmail.com';
       $subject = 'Contact Request From Website';
       $headers = "From: ".$name." <".$email."> \r\n";
       $send_email = mail($to,$subject,$message,$headers);

       echo ($send_email) ? 'success' : 'error';

  }?>

【讨论】:

  • 嗨,谢谢,当我将我的 php 移动到不同的文件位置并在 ajax url 中显示路径时它起作用了。但是我发现另一个问题,虽然它正在发送邮件,但它总是显示错误消息而不是成功味精
  • @Mithu 我不确定 $send_email 变量包含什么?如果您将最后一行更改为 echo ($send_email != false) 怎么办? '成功' : '错误';
  • 何时更改为 ($send_email != false) ? “成功”:“错误”;它没有发送邮件,也没有显示任何消息
  • 嗯,好吧,对不起。我不确定 mail() 函数应该如何响应。但它看起来像是在响应错误或哈希 - 在您的 if 速记语句中总是错误的。请参阅此处的回复部分:w3schools.com/php/func_mail_mail.asp
猜你喜欢
  • 2015-08-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-07-13
  • 1970-01-01
  • 2012-07-02
  • 2017-07-21
相关资源
最近更新 更多