我已在html中设置了联系表单,但每当用户提交邮件时,页面都会重新加载。我已经看到了一些可以使用ajax纠正这个问题的例子,但我不确定如何解决这个问题。这是我的表单,以及它背后的php代码:
<form id="email-form" action="index.html" method="post" role="form" target="_blank">
<div class="row">
<div class="col-md-6">
<label for="name">Name</label>
<input type="text" class="form-input" name="name" id="name" value="" placeholder="Enter your name">
</div>
<div class="col-md-6">
<label for="email">Email</label>
<input type="email" class="form-input" name="email" id="email" value="" placeholder="Enter your email">
</div>
</div>
<div class="row">
<div class="col-md-12">
<label for="message">Message</label>
<textarea rows="6" id="message" name="message" class="form-input" placeholder="Talk to us about maths!"></textarea>
</div>
</div>
<div class="row">
<div class="col-md-12">
<button class="main-button" type="submit" id="submit">Send Message</button>
</div>
</div>
</form>
<?php
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$from = 'Maths website';
$to = 'my@email.com';
$subject = 'Maths Message';
$body = "From: $name\n E-Mail: $email\n Message:\n $message";
if ($_POST['submit']) {
if ($name != '' && $email != '') {
if (mail ($to, $subject, $body, $from)) {
echo '<p>Your message has been sent!</p>';
} else {
echo '<p>Something went wrong, go back and try again!</p>';
}
} else {
echo '<p>You need to fill in all the fields!</p>';
}
}
另外 - 请注意,表单标记包含action="index.html"
。这仍然有效吗?我已将AddType application/x-httpd-php .html .htm
行添加到我的.htaccess文件中,但我不确定这是否适用于操作密钥。
答案 0 :(得分:0)
使用以下代码进行必要的修改:
<form action="index.php" method="post"id="formid" >
<input id="name" type="text" name="name" required><br><br>
<input id="password" type="password" name="password" required><br>
<input type="submit" id="submit" name="submit">
</form>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script>
$(document).ready(function(){
$("#submit").click(function() {
var name= $("#name").val();
var password= $("#password").val();
$.ajax({
type: "POST",
url: "insert.php",
data: "name=" + name+ "&password=" + password,
success: function(data) {
alert("sucess");
}
});
});
});
</script>
<?php //insert.php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "ajax";
// Create connection
$conn = new mysqli($servername, $username, $password,$dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$name=$_POST['name'];
$pass=$_POST['password'];
$sql=mysqli_query($conn, "INSERT INTO insert_tbl(name,pass) VALUES('".$name."','".$pass."')")
?>