代码之家  ›  专栏  ›  技术社区  ›  mikebrsv

无法将数据jquery发布到phpmailer

  •  0
  • mikebrsv  · 技术社区  · 6 年前

    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 .

    当我在js文件中记录数据时,它可以正常工作,但是 $_POST["email"] 在后台返回时 null . 我试过

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

    在我的JS中,也不起作用。

    3 回复  |  直到 6 年前
        1
  •  1
  •   Jerdine Sabio    6 年前

    在Post中,对象被包含在数据属性中。因此,您可能需要通过访问php文件中的数据;

    $_POST['data'];
    

    因为它是一个物体,你必须解码

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

    然后使用访问它;

    $data['email'];
    

    确保在Ajax中使用类似于此数据属性的格式;

    data: { 'email':'test@test.com' }
    
        2
  •  0
  •   You Nguyen    6 年前

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

    这个 $form.serialize() 返回字符串,而不是 对象 .

    例子:

    使用 $.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/

        3
  •  0
  •   mikebrsv    6 年前

    结果发现问题是由这些.htaccess规则引起的,这些规则用于隐藏 .php URL中的扩展名:

    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]