在我的INDEX.HTML页面上,我有一个订阅表单,该表单使用php将数据写入数据库。一切正常。

当我提交表单时,站点将转到PHP文件,我使用该文件向我和访问者提交电子邮件。然后,我可以回声谢谢消息。但是...我不希望该消息出现在此php页面中....我希望表单消失并且该消息出现在我的索引页面的一个标签中...例如一个DIV。

我该怎么做呢?如果我需要使用AJAX或JQUERY ...您能指出我正确的地方吗?

以下是一些代码:

 <div class="container-fluid">
 <form action="thankyou.php" method="post">
     <div class="form-group">
       <label for="firstname">First Name:</label>
       <input type="input" class="form-control" id="firstname"  name="firstname">
       <label for="lastname">Last Name:</label>
       <input type="input" class="form-control" id="lastname" placeholder="" name="lastname">
       <label for="email">Email:</label>
       <input type="email" class="form-control" id="email" placeholder="" name="email">
       </div>
       <button type="submit" class="btn btn-warning">Submit</button>
   </form>
   </div>


Thankyou.php

<?php

require 'connection.php';
$conn         = Connect();
$firstname    = $conn->real_escape_string($_POST['firstname']);
$lastname     = $conn->real_escape_string($_POST['lastname']);
$email        = $conn->real_escape_string($_POST['email']);
$myemail      = "myemailaddress";
$query        = "INSERT into subscription (firstname,lastname,email) VALUES('" . $firstname . "','" . $lastname . "','" . $email . "')";
$success      = $conn->query($query);
$subject1     = "New eBook Subscriber";


if (!$success) {
    die("Couldn't enter data: ".$conn->error);
} else {

  $headers  = "MIME-Version: 1.0" . "\r\n";
  $headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
  $headers .= 'From: ' .$myemail. "\r\n";


 $message = "some message";

  $messageb = "some message";

  mail($email, $subject, $messageb, $headers);
  mail($myemail, $subject1, $message, $headers);

?><META HTTP-EQUIV="Refresh" CONTENT="1;URL=index.html">

<?php
$conn->close();
}
?>

最佳答案

试试这个解决方案

<div class="container-fluid">
 <form action="thankyou.php" method="post" id="form">
     <div class="form-group">
       <label for="firstname">First Name:</label>
       <input type="input" class="form-control" id="firstname"  name="firstname">
       <label for="lastname">Last Name:</label>
       <input type="input" class="form-control" id="lastname" placeholder="" name="lastname">
       <label for="email">Email:</label>
       <input type="email" class="form-control" id="email" placeholder="" name="email">
       </div>
       <button type="submit" class="btn btn-warning">Submit</button>
   </form>
   </div>

<script>


$('#form').on('submit', function(event) {
 event.preventDefault(); //stops form on submit
  var formData = {};
  $.each($("#form").serializeArray(), function (i, field) {
    formData[field.name] = field.value;
  });
  $.ajax({
  url: 'thankyou.php',
  data: formData,
  method:'POST',
  success: function(response) {
   $(this).hide(); //sets css display:none to form
   var message = "Thank you!";
   $('.container-fluid').html(message);
   }
});

});
</script>

10-02 04:10
查看更多