【问题标题】:Ajaxifying php page result dataAjaxifying php 页面结果数据
【发布时间】:2018-02-26 20:21:00
【问题描述】:

填写联系我们表格后,我想通过用户向 domain@host.com 发送邮件。 在这两种情况下成功发送或发送失败消息都显示在新页面中,我想在提交后在我的联系我们页面上显示这些消息。

html

    <form  id="form"class="form" action="sendEmail.php" method="POST">

    <p class="name">
        <input type="text" name="name" id="name" placeholder="John Doe" />
        <label for="name">Name</label>
    </p>

    <p class="email">
        <input type="text" name="email" id="email" placeholder="mail@example.com" />
        <label for="email">Email</label>
    </p>

    <p class="subject">
        <input type="text" name="subject" id="subject" placeholder="www.example.com" />
        <label for="subject">subject</label>
    </p>        

    <p class="text">
        <textarea name="message" id="comment" placeholder="Write something to us" /></textarea>
    </p>
              <div id="complete" class="complete hide">
        <h3>Thank you</h3>
        <p>We will be in contact with you soon!</p>
      </div>
    <p class="submit">
        <input type="submit" value="Send" />
    </p>




</form>

这是我的 sendEmail.php 代码

        <?php
    $toAddress = 'domain@host.com'; //eamil will be sent to this account...
    $EmailSentBy= $_POST['email'];
    $userEmail = $_POST['name'];
    $title = $_POST['subject'];
    $message = $_POST['message'];
    //****************************************************************


    require 'PHPMailer-5.2.23/PHPMailerAutoload.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 = 0;

    //Ask for HTML-friendly debug output
    $mail -> Debugoutput = 'html';

    //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 = "domain@host.com";//email address from which it is send to other // 

    //Password to use for SMTP authentication
    $mail -> Password = "ooovxxazwdbxmcgn";//password of website email account

    //Set who the message is to be sent from
    $mail -> setFrom($toAddress, "Contact Us Page");

    //Set an alternative reply-to address
    $mail -> addReplyTo($userEmail, "UserName here");

    //Set who the message is to be sent to
    $mail -> addAddress($toAddress, "Mr/Mrs.");//receiver

    //Set the subject line
    $mail -> Subject = $title;


    $msg = 'Message';

    //$mail->msgHTML(file_get_contents('contents.html'), dirname(__FILE__));
    $mail -> msgHTML($msg);

    //Replace the plain text body with one created manually
    $mail -> AltBody = 'This is an auto generated email from oric.uob.edu.pk';

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


    //************************************************************************
    if (!$mail -> send()) {

   echo json_encode(array('status' => false, 'msg' => 'There was a problem while sending Email' . $mailer -> ErrorInfo));

die();

}else{

echo json_encode(array('status' => TRUE, 'msg' => 'Successfully Approved'));
die();
    }
    ?>

Jscript

    $(function() {
  var form = $('#form');


  $(form).submit(function(event) {

    event.preventDefault();
    var formData = $(form).serialize();

    $.ajax({
        type: 'POST',
        url: $(form).attr('action'),
        data: formData
    })
    .done(function(response) {
      response=$("#msg").html("<i>Thank you </i>")

    })
    .fail(function(data) {

    });
  })
});

我无法找出问题所在,非常感谢任何形式的帮助。 提前致谢。

【问题讨论】:

  • 你在开玩笑吗?如果你甚至不在 Jscript 中调用它们,你应该如何实现你想要的。
  • 您需要提供minimal reproducible example。您的问题中缺少包含您的表单的页面的 HTML。 PHP 在很大程度上是无关紧要的(至少除非你已经调试了足够多的东西以确定你从 PHP 得到错误的响应)。
  • 我收到了响应但它重定向到其他页面并在那里显示响应数据
  • 开发者工具的控制台有报错吗? (确保您已将其配置为在页面加载之间保留日志)。
  • @naizoric — 发表评论时,没有 &lt;form&gt; 可附加到该事件。

标签: php ajax phpmailer


【解决方案1】:

您没有从 Jscript 中的 sendEmail.php 正确获取结果数据,因为您在 echo json_encode(array('status' =&gt; false, 'msg' =&gt; 'There was a problem while sending Email' . $mailer -&gt; ErrorInfo)); 中使用了 Status 和 msg 您应该在表单标签中删除 method=post ,同时使用这两种方法可能会给您带来麻烦 创建 Jscript 函数并在您的 submint 按钮中使用 onClick 属性。

<input type="submit" onClick="myfun()"/>

Jscript

function myfun()
{
        var data = $("#loginForm").serialize();// form ki id 

    $.ajax({
    method : "POST",
    url : "process/login.php",  //process file
    dataType : "json",
    //data : data,
    }).done(function(data) {
    status = data["status"];


    if (status == true | status=="true") {
    msg1 = data["msg"];
    msg = msg1;
    alert(msg);

    } else {

    msg1 = data["msg"];
    // alert(msg);
    msg = msg1;
    var Error_message = '<div class="alert alert-danger alert-dismissible" role="alert"><button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>  <strong> <i class="fa fa-exclamation-triangle" aria-hidden="true"></i></strong>  ' + msg + '</div>';
    response.html(Error_message);

    }

    }).fail(function(x, y, z) {
    var msg = x.responseText;
    alert(msg);

    response.html(x + y + z);
    });
}

这样就可以了。

【讨论】:

  • “你没有从 Jscript 中的 sendEmail.php 获取结果数据,因为你在你的中使用了 Status 和 msg”——使用这些特定的键名如何防止 JavaScript 接收数据?跨度>
  • "在您的 submint 按钮中使用 onClick 属性" — 不要那样做! (a) 现在不是 1997 年。我们有能力从 JavaScript 绑定事件处理程序(现有代码已经在这样做)。 (b) 现在您不再阻止表单提交的默认操作,这将产生问题所描述的问题。
  • @Quentin 你注意到我的代码中有 status = data["status"] 吗?我建议的方法解决了他的问题。执行我提出的任务的方法不止一种。
  • @Quentin 使用特定的键名不会阻止 javascript 接收数据,但不会像您希望他们喜欢的那样执行,如果 status =true 执行此操作,否则执行此操作..
【解决方案2】:

我认为您应该选择通过 POST(使用 &lt;form method="POST"&gt; 或通过 ajax 使用 $.ajax())提交表单数据,但您不应该同时使用两者。

目前,您的 Javascript 被绕过:当您点击提交按钮时,浏览器正在请求 sendEmail.php 并等待响应而不调用您的 JavaScript。

如果你想让渲染后的sendEmail.php显示在同一页面上,你应该改变

<input type="submit" value="Send" />

<button id="sendmail">Send</button>

然后用 Jquery 选择它

$('#sendmail').on('click', function(e) { /* your AJAX goes here */ });

此外,您应该知道,能够生成 POST 请求的每个人都将能够滥用您的 PHP 脚本并使用您的邮件帐户发送任意电子邮件

【讨论】:

  • “但你不应该同时使用两者”——这是个糟糕的建议。不显眼的 JavaScript / 渐进式增强是一种很好的设计理念。
  • "当您单击提交按钮时,浏览器正在请求 sendEmail.php 并等待响应而不调用您的 JavaScript" — 不应该。 JavaScript 正在绑定一个提交事件处理程序,以防止表单的默认操作。
  • &lt;button id="sendmail"&gt;Send&lt;/button&gt; — 默认按钮类型为 submit,因此完全没有区别。
猜你喜欢
  • 1970-01-01
  • 2014-03-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-12-30
  • 2013-06-17
  • 2011-11-10
相关资源
最近更新 更多