在同一页面上响应的 PHP 表单


嗨,我

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

这是提交后的输出:

{"状态":"成功","留言":"感谢您对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>

这是联系人提交.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("rn", $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;
?>```

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

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

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

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

尝试此编辑:

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

我已经调试了您的代码并测试了它是否正常工作。您需要添加以下 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。 更改此设置:

<div id="response_msg">

对此:

<div class="response_msg">

或者更改选择器以改为引用类。

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

最新更新