在同一页面上提交带有成功/失败警报的联系表单

时间:2018-08-01 13:50:47

标签: javascript php html ajax twitter-bootstrap

正如您在代码中看到的那样,我有html,php,js和ajax的联系表。成功填写表格并单击提交后,电子邮件已成功发送。但是成功消息无法在同一页面上看到。它会看到另一页。这是代码。你能帮我我想念或做错的事吗?谢谢您的帮助。

--- HTML代码---

<div class="container">
 <div class="row">
  <div class="col-xl-8 offset-xl-2">
   <h1>CONTACT FORM</h1><hr>
   <p class="lead">By filling out the contact form; You may have information about us and current news.</p>
   <form id="contact-form" method="post" action="contact.php" role="form" novalidate="true">
   <div class="messages"></div>
   <div class="controls">
    <div class="row">
     <div class="col-lg-6">
      <div class="form-group">
        <label for="form_name">Full Name *</label>
        <input id="form_name" type="text" name="name" class="form-control" placeholder="Please fill the name field *" required="required" data-error="You must fill the name field">
        <div class="help-block with-errors alert-danger"></div>
       </div>
      </div>
      <div class="col-lg-6"></div>
    </div>
    <div class="row">
     <div class="col-lg-6">
      <div class="form-group">
       <label for="form_email">E-mail *</label>
       <input id="form_email" type="email" name="email" class="form-control" placeholder="Please fill the email field *" required="required" data-error="You must fill the email field">
        <div class="help-block with-errors alert-danger"></div>
       </div>
      </div>
      <div class="col-lg-6"></div>
    </div>
    <div class="row">
     <div class="col-lg-6">
      <div class="form-group">
       <label for="form_subject">Subject *</label>
       <input id="form_subject" type="text" name="subject" class="form-control" placeholder="Please fill the subject field *" required="required" data-error="You must fill the subject field">
        <div class="help-block with-errors alert-danger"></div>
       </div>
      </div>
      <div class="col-lg-6"></div>
     </div>
     <div class="form-group">
      <label for="form_message">Message *</label>
      <textarea id="form_message" name="message" class="form-control" placeholder="Please fill the message field *" rows="4" required="required" data-error="You must fill the message field"></textarea>
       <div class="help-block with-errors alert-danger"></div>
      </div>
      <input type="submit" class="btn btn-success btn-send" value="Submit">
      <p class="text-muted" style="padding-top: 5px;"><strong>*</strong>This field must be fill.</p>
      </div><!-- controls all end -->
     </form><!-- form all end -->
    </div><!-- col-xl-8 offset-xl-2 end -->
   </div><!-- row all end -->
 </div><!-- container all end -->

--- PHP代码---

$from = '';
$sendTo = 'email@email.com';
$subject = 'New message from contact form';
$fields = array('name' => 'Name', 'email' => 'Email', 'subject' => 'Subject', 'message' => 'Message');

$okMessage = 'Thank you for your message. I will write back soon.';
$errorMessage = 'There is an error while sending message. Please try again later.';

try {if (!empty($_POST)) {
    $emailText = "You have a new message from your contact form\n=====\n";
    foreach ($_POST as $key => $value) {
       if (isset($fields[$key])) {
         $emailText .= "$fields[$key]: $value\n";
       }
    }
    $headers = array('Content-Type: text/plain; charset="UTF-8";',
     'From: ' . $from,
     'Reply-To: ' . $from,
     'Return-Path: ' . $from,
    );
    mail($sendTo, $subject, $emailText, implode("\n", $headers));
    $responseArray = array('type' => 'success', 'message' => $okMessage);
    }
}
catch (\Exception $e) {
  $responseArray = array('type' => 'danger', 'message' => $e->getMessage());
}
if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
 $encoded = json_encode($responseArray);
 header('Content-Type: application/json');
 echo $encoded;
} else {
echo $responseArray['message'];
}

--- JS和AJAX代码---

$(function () {
  $('#contact-form').on('submit', function (e) {
   if (!e.isDefaultPrevented()) {
    var url = "contact.php";

    $.ajax({
     type: "POST",
     url: url,
     data: $(this).serialize(),
     success: function (data) {
      var messageAlert = 'alert-' + data.type;
      var messageText = data.message;
      var alertBox = '<div class="alert ' + messageAlert + ' alert-dismissable"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>' + messageText + '</div>';
      if (messageAlert && messageText) {
       $('#contact-form').find('.messages').html(alertBox);
       $('#contact-form')[0].reset();
      }
     }
    });
    return false;

   }
  })
});

2 个答案:

答案 0 :(得分:0)

如果我正确理解了您的问题,那么当您提交表格时,您会被重定向吗? 为此,我建议您删除操作表单的属性。然后尝试:

$ ('#contact-form'). On ('submit', function (e) {
e.preventDefault();
e.stopPropagation();
...

您必须声明e.preventDefault(); 在检查if(!event.isDefaultPrevented())

之前

答案 1 :(得分:0)

感谢大家的帮助和指导,以解决问题。

最重要的是,我在没有 action =“ contact.php”

的情况下更改了该行

-旧样式---

<form id="contact-form" method="post" action="contact.php" role="form" novalidate="true">

-新样式---

<form id="contact-form" method="post" role="form" novalidate="true">

第二个,在正文中,我有 jquery-3.3.1.slim.min.js 库,但是该库没有 AJAX ,因此我将其更改为 jquery-3.3.1.min.js

现在,一切正常。