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

时间:2018-04-29 12:26:27

标签: php ajax email

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

当我尝试发送电子邮件时,它不会发送任何电子邮件并始终触发AJAX错误消息。我在与AJAX的AJAX集成方面做得不是很好。

以下是我的代码

deny from all

1 个答案:

答案 0 :(得分:2)

我会将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';

  }?>