无法将数据jQuery发布到phpmailer

时间:2018-10-03 00:54:48

标签: javascript php jquery phpmailer

HTML格式:

<form id="contacts-form">
  <input name="email" type="text">
  <textarea name="contacts-form-textarea"></textarea>
  <button type="submit">Send</button>
</form>

JS:

var $form = $("#contacts-form");
$form.on("submit", submitHandler);

function submitHandler(e) {
  e.preventDefault();
  $.ajax({
    url: '/sendmail2.php',
    type: 'POST',
    data: $form.serialize()
  }).done(response => {
    if (JSON.parse(response).success) {
      console.log('success');
      $form.trigger('reset');
    } else {
      console.log('fail');
    }
  });
}

sendmail2.php(基本上是对official phpmailer example for gmail进行了少量修改):

<?php
//Import PHPMailer classes into the global namespace
use PHPMailer\PHPMailer\PHPMailer;

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

//Create a new PHPMailer instance
$mail = new PHPMailer;

//Tell PHPMailer to use SMTP
$mail->isSMTP();

//Enable SMTP debugging
// 0 = off (for production use)
// 1 = client messages
// 2 = client and server messages
$mail->SMTPDebug = 2;

//Set the hostname of the mail server
$mail->Host = 'smtp.gmail.com';
// use
// $mail->Host = gethostbyname('smtp.gmail.com');
// if your network does not support SMTP over IPv6

//Set the SMTP port number - 587 for authenticated TLS, a.k.a. RFC4409 SMTP submission
$mail->Port = 587;

//Set the encryption system to use - ssl (deprecated) or tls
$mail->SMTPSecure = 'tls';

//Whether to use SMTP authentication
$mail->SMTPAuth = true;

//Username to use for SMTP authentication - use full email address for gmail
$mail->Username = "myemail@gmail.com";

//Password to use for SMTP authentication
$mail->Password = "mypass";

//Set who the message is to be sent from
$mail->setFrom('from@example.com', 'First Last');

//Set an alternative reply-to address
$mail->addReplyTo('replyto@example.com', 'First Last');

//Set who the message is to be sent to
$mail->addAddress('anotherone@gmail.com', 'My Name');

//Set the subject line
$mail->Subject = 'PHPMailer GMail SMTP test';

//Read an HTML message body from an external file, convert referenced images to embedded,
//convert HTML into a basic plain-text alternative body
// $mail->msgHTML(file_get_contents('contentss.html'), __DIR__);
$mail->msgHTML('<h1>' . $_POST["email"] . '</h1>');

//Replace the plain text body with one created manually
$mail->AltBody = 'This is a plain-text message body';

//Attach an image file
// $mail->addAttachment('images/phpmailer_mini.png');

//send the message, check for errors
if (!$mail->send()) {
    // echo "Mailer Error: " . $mail->ErrorInfo;
    $results = array('success' => false);
    echo json_encode($results);
} else {
    // echo "Message sent!";
    $results = array('success' => true);
    echo json_encode($results);
    //Section 2: IMAP
    //Uncomment these to save your message in the 'Sent Mail' folder.
    #if (save_mail($mail)) {
    #    echo "Message saved!";
    #}
}

//Section 2: IMAP
//IMAP commands requires the PHP IMAP Extension, found at: https://php.net/manual/en/imap.setup.php
//Function to call which uses the PHP imap_*() functions to save messages: https://php.net/manual/en/book.imap.php
//You can use imap_getmailboxes($imapStream, '/imap/ssl') to get a list of available folders or labels, this can
//be useful if you are trying to get this working on a non-Gmail IMAP server.
function save_mail($mail)
{
    //You can change 'Sent Mail' to any other folder or tag
    $path = "{imap.gmail.com:993/imap/ssl}[Gmail]/Sent Mail";

    //Tell your server to open an IMAP connection using the same username and password as you used for SMTP
    $imapStream = imap_open($path, $mail->Username, $mail->Password);

    $result = imap_append($imapStream, $path, $mail->getSentMIMEMessage());
    imap_close($imapStream);

    return $result;
}

邮件发送正常,我在电子邮件中收到了邮件。但是由于某些原因,data并未发送到sendmail2.php

当我console.log JS文件中的数据时,它可以正常工作,但是后端上的$_POST["email"]返回null。我尝试过

var data = {
  email: $("#contacts-form input").val()
};

在我的JS中也没有用。

3 个答案:

答案 0 :(得分:1)

在POST中,对象包含在data属性中。因此,您可能必须通过以下方式访问PHP文件中的数据;

$_POST['data'];

因为它是一个对象,所以您必须解码

$data = json_decode( $_POST['data'], true);

然后使用;

$data['email'];

确保像这样在ajax中具有这种数据属性的格式;

data: { 'email':'test@test.com' }

答案 1 :(得分:0)

使用$.ajax({})将数据发送到服务器时,data属性应该是object,而不是string

$form.serialize()返回一个字符串,而不是object

示例:

使用$.ajax()将一些数据保存到服务器,并在完成后通知用户。

$.ajax({
  method: "POST",
  url: "some.php",
  data: { name: "John", location: "Boston" }    // it needs an object, not a string
})
  .done(function( msg ) {
    alert( "Data Saved: " + msg );
  });

更多信息,请点击此处:http://api.jquery.com/jquery.ajax/

答案 2 :(得分:0)

原来,问题是由以下.htaccess规则引起的,这些规则用于在网址中隐藏.php扩展名:

RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s/+(.+?)\.php[\s?] [NC]
RewriteRule ^ /%1 [R=301,L,NE]

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.+?)/?$ $1.php [QSA,NC,L]

除此之外,初始帖子中的代码按预期工作。

添加:

以上规则可以替换为以下规则(不影响邮件发送):

RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule !.*\.php$ %{REQUEST_FILENAME}.php [L]