简体   繁体   English

使用 AJAX 在 PHP 中发送电子邮件

[英]Sending email in PHP using AJAX

I am trying to send email in PHP using AJAX in a simple contact form.我正在尝试在简单的联系表单中使用 AJAX 在 PHP 中发送电子邮件。 I have the following codes for a simple form, PHP code for submit button and AJAX script.我有以下用于简单表单的代码、用于提交按钮的 PHP 代码和 AJAX 脚本。

When I am trying to send email it is not sending any email and always firing the AJAX error msg.当我尝试发送电子邮件时,它不发送任何电子邮件并且总是触发 AJAX 错误消息。 I am not very well in AJAX integration with PHP.我不太擅长将 AJAX 与 PHP 集成。

Below is my code下面是我的代码

 <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>

I would move the php part to another file:我会将 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>

And in another email.php在另一个 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';

  }?>

So, the top answer works, but as @Mithu said, for some reason it always says: 'Error Sending email!'所以,最重要的答案是有效的,但正如@Mithu 所说,出于某种原因,它总是说:“发送电子邮件时出错!” So, after 30 minutes of exploring the situation I understood that for some reason it returns from PHP not 'success' but ' success' with 3 spaces.因此,经过 30 分钟的探索,我明白出于某种原因,它从 PHP 返回的不是“成功”而是带有 3 个空格的“成功”。 So, all you need is to exclude these 3 spaces and also to make another if else statement in the PHP to check FALSE instead of TRUE.因此,您只需要排除这 3 个空格,并在 PHP 中创建另一个 if else 语句来检查 FALSE 而不是 TRUE。 Here how it looks and works for me:这是它的外观和对我的工作方式:

HTML: HTML:

<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>

JS: 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({
                    url: "email.php",
                    method: form.attr('method'),
                    data: form.serialize(),
                    success: function(result){
                let y = result.substring(3);
                if (y == '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:

 <?php

    $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 'error';
   } else {
     echo 'success';}
   ?>

So, if the original code of @Bolli doesn't work on your website, try this code, it work very well on my side.所以,如果@Bolli 的原始代码在你的网站上不起作用,试试这个代码,它在我这边工作得很好。

You must be stop the default flow of that form by using event.preventDefault();您必须使用event.preventDefault();停止该表单的默认流程event.preventDefault(); and you can pass the form as multipart/formdata or form-data and check the developer tools -> network -> fetch/xhr -> payload/ formdata .您可以将表单作为 multipart/formdata 或 form-data 传递并检查developer tools -> network -> fetch/xhr -> payload/ formdata then you create a seperate page in php and do the mail process in that page and change the form action link to that page然后您在 php 中创建一个单独的页面并在该页面中执行邮件处理并将表单操作链接更改为该页面

In html在 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>

In php - mail.php在 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);    
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM