【问题标题】:PHP form with response on same page在同一页面上响应的 PHP 表单
【发布时间】:2019-07-12 14:02:47
【问题描述】:

您好,我创建了一个 PHP 表单 - 我收到了电子邮件,但响应消息在同一个窗口中以纯文本形式打开。如果有人能指出我正确的方向,那就太好了。

这是提交后的输出:

{"status":"success","message":"感谢您对 Nature's Apprentice 的关注。 代表将尽快与您联系","email_sent":true}

这是联系表格代码:

<form name="formContact" id="formContact" action="contact-submit.php" method="post" novalidate="novalidate">

            <label for="name">Name <span class="required" >*</span></label>
            <input name="name" id="name" class="form-control " placeholder="First and Last Name" type="text">

            <label for="email">Email <span class="required" >*</span></label>
            <input name="email" id="email" class="form-control" placeholder="email@domain.com" type="text">

            <label for="phone">Phone</label>
            <input name="phone" id="phone" class="form-control" placeholder="(xxx) xxx-xxxx" type="text">

            <label for="address">Area of Interest </label>
            <input name="address" id="address" class="form-control" placeholder="Location" type="text">

            <label for="comments">Comments</label>
            <textarea name="comments" id="comments" placeholder=""></textarea>

            <input name="submit" id="submit" class="submit_btn" value="Submit" type="submit">
            <img src="images/loader.gif" alt="Loader" class="loader">
            <div class="info_msg">
                <p><span class="required">*</span> indicates required field.</p>
            </div>
            <div class="response_msg">
                <p></p>
            </div>
</form>

这是js:


   jQuery(document).ready(function ($) {
       $("#formContact").validate({
           ignore: ".ignore",
           rules: {
               name: "required", 
               email: {
                   required: true, 
                   email: true
               }
           }, 

           invalidHandler: function (form, validator) {
               $('#formContact').find('#response_msg p').removeClass().addClass('error').html('Please fill all the required fields.');
           }, 
           submitHandler: function (form) {
               $.ajax({
                   type: "POST", 
                   url: $(form).attr('action'), 
                   data: $(form).serialize(), // serializes the form's elements.
                   beforeSend: function(){
                       $('img.loader').fadeIn();
                   },
                   success: function (data) {

                       var json = $.parseJSON(data);

                       //alert(json.status , json.message);

                       $('#formContact').find('#response_msg p').removeClass().html('');

                       if(json.status !='') {

                           if(json.status == 'success') {
                               $('#formContact').trigger('reset');
                           }                    

                           setTimeout(function(){
                               $('#formContact').find('#response_msg p').removeClass().addClass(json.status).html(json.message).fadeIn();
                           }, 1000);

                       }

                   },
                   error:function (xhr, ajaxOptions, thrownError){
                       $('#formContact').find('#response_msg p').removeClass().addClass('error').html('Some error occured. Please try again.').fadeIn();
                   },
                   complete: function(){
                       $('img.loader').fadeOut();
                   }
               });
           }
       });
   });
</script>

这是contact-submit.php:


    //session_start(); 
    require 'include/include.php';
    $name = trim($_POST['name']);
    $email = trim($_POST['email']);
    $phone = trim($_POST['phone']);
    $address = trim($_POST['address']);

    $comments = trim($_POST['comments']);

    $errors = array();

    if($name == '' or $email == '' ) {
        $response = array('status' => 'error', 'message' => 'Please fill all the required fields.');
        echo json_encode($response);
        exit;
    }
    else {

        if(strlen($name) < 3) {
            $errors[] = 'Name should be 3 characters long.';    
        }


        $email = filter_var($email, FILTER_SANITIZE_EMAIL);

        if (filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
            $errors[] = 'Please enter valid email.';
        } 

        $errors = array_filter($errors);

        if (!empty($errors)) { 
            $message = implode("<br>", $errors);
            $response = array('status' => 'error', 'message' => $message );
            echo json_encode($response);
            exit;    
        }
        else { 
            $mailsubject = "Contact Us Form Details - ".$site_name;
            $sendmessage = "Dear Administrator,<br /><br />     
                <b>Name:</b> $name<br /><br />
                <b>Email:</b> $email<br /><br />
                <b>Phone:</b> $phone <br /><br />
                <b>Address:</b> $address <br /><br />
                <b>Comments:</b> $comments <br /><br />";
            $mail_str = "";
            $mail_str = '<html><head><link href="http://fonts.googleapis.com/css?family=Open+Sans" rel="stylesheet" type="text/css"></head><body style="max-width: 600px; margin: 0 auto; font-family: Open Sans, sans-serif; font-size: 15px; line-height: 20px;"> <table style="border:1px solid #000000" width="95%" align="center" cellspacing="0" cellpadding="0"> <tbody><tr style="background-color:#365744"><td style="padding: 10px; "><a href="#" style="color: #fff; font-weight: bold; font-size: 40px; text-decoration: none; display: block; line-height: normal;">'.$site_name.'</a></td></tr><tr style="background-color:#ffffff"><td style="padding: 10px; ">'.$sendmessage.' </td></tr><tr style="background-color:#383634; color: #fff;"><td style="padding: 10px; ">Thanks! - '.$site_name.'</td></tr></tbody></table></body></html>';                

            // To send HTML mail, the Content-type header must be set
            $headers[] = 'MIME-Version: 1.0';
            $headers[] = 'Content-type: text/html; charset=iso-8859-1';

            // Additional headers
            $headers[] = sprintf('From: %s <%s>', $name, $email);

            $headers = implode("\r\n", $headers);

            #echo "<hr/>"; echo $to_mail;echo "<hr/>";echo $mailsubject;echo $mail_str; echo $headers; exit;    

            $emailsend = mail($admin_email, $mailsubject, $mail_str, $headers);

            if($emailsend) {
                $response = array('status' => 'success', 'message' => sprintf('Thank you for your interest in %s. <br /> A representative will be in contact with you shortly', $site_name), 'email_sent' => $emailsend);
                echo json_encode($response);
                exit;
            }
            else {
                $response = array('status' => 'error', 'message' => 'Some error occured. Please try again.', 'email_sent' => $emailsend);
                echo json_encode($response);
                exit;
            }
        }
    }

    #---------------Mail For Admin (Ends)--------------------------------------------------

    //header("Location:thank-you.html");
    exit;
?>```

【问题讨论】:

  • 这听起来像是您的 JS 代码没有做太多事情,并且表单会“正常”发送……您确定您在那里使用的任何库/插件都希望表单具有 novalidate="novalidate"放 …?这听起来有点违反直觉。
  • json.status == 'success'里面你可以$('.response_msg').html(json.message)
  • 也许在你的submitHandler ajax 调用之前添加peventDefault()。您需要将event 参数添加到submitHandler,然后执行event.preventDefault()
  • 查看我的代码有 class="response_msg" 然后 #response_msg 我从未更新过它。但不管是class还是id都行不通
  • 你从哪里得到.validate() 函数?您粘贴的项目无法加载。

标签: php html forms submit contacts


【解决方案1】:

根据您的代码 class="response_msg" 在您的表单中应该是 id="response_msg"。

您应该在返回 json 时设置标头。

header('Content-Type: application/json');

【讨论】:

  • 我对此添加了评论。一切都是类还是 id 都没有关系。我在这里复制代码时忘记将代码改回来。不过谢谢!
  • 我已经更新了我的答案。我刚刚注意到您没有为 json 内容类型设置标头。
  • 在返回响应之前设置标题。所以在你的 echo json_encode($response);.
  • 您应该在提交处理程序中调用 preventDefault() 和 stopPropagation() ,就像其他评论中提到的那样。否则你最终会得到正常的表单提交行为。
【解决方案2】:

尝试添加preventDefault 电话。否则,表单可能在您的 Ajax 完成后通过正常的表单 POST 过程提交,因此重定向到 contact-submit.php 页面,您会在空白页面上看到响应的回显。

试试这个编辑:

...
submitHandler: function (form, e) {
    e.preventDefault();
    $.ajax({
        type: "POST"
...

【讨论】:

  • 我只是尝试了一下,没有运气。不过谢谢!
【解决方案3】:

我已经调试了您的代码并对其进行了测试。您需要添加以下 4 项更改:

  1. 将数据类型指定为 jQuery。如下添加dataType 行。

data: $(form).serialize(), // serializes the form's elements. dataType: 'json', beforeSend: function(){

  1. 让 jQuery 进行 JSON 解析。改变这个:

success: function (data) {

到这里:

success: function (json) {

  1. 去掉这条线:

var json = $.parseJSON(data);

  1. 您的#response_msg 选择器已关闭,因为您为容器指定了.response_msg 类,而不是ID。改变这个:

&lt;div id="response_msg"&gt;

到这里:

&lt;div class="response_msg"&gt;

或者将选择器改为引用类。

然后事情应该会按预期工作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多