Отправка электронной почты в PHP с использованием AJAX - PullRequest
0 голосов
/ 29 апреля 2018

Я пытаюсь отправить письмо на PHP с помощью AJAX в простой контактной форме. У меня есть следующие коды для простой формы, код 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>

1 Ответ

0 голосов
/ 29 апреля 2018

Я бы переместил часть 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';

  }?>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...