我一直在尝试使用jquery ajax提交表单并尝试该页面不应重新加载或刷新,但这些目标都没有完成。我错过了什么吗?
形式
<form method="POST" id="formReviews">
<div>
<label><b>Name</b></label>
<input style="width:400px;" type="text" class="form-control" placeholder="Enter your name" name="txtName" required>
</div>
<div>
<label><b>Area</b></label>
<input style="width:400px;" type="text" class="form-control" placeholder="Enter the area you would want to improvise" name="txtArea" required>
</div>
<div>
<label><b>Details</b></label>
<textarea style="width:400px;" type="comment" class="form-control" row="5" placeholder="Enter the some details" name="txtDetails" required></textarea>
</div>
<br>
<div>
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</form>
jquery的:
$(document).on('submit','formReviews',function(e){
$.ajax({
url: $(this).attr('action'),
type: $(this).attr('method'),
data: $(this).serialize(),
success: function(html){
alert('Review Submitted');
}
});
e.preventDefault();
});
reviews.php
<?php
$servername = "localhost:3306";
$username = "mebe";
$password = "bethe";
$dbname = "SpecsCompare";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql="INSERT INTO reviews (Name, Area, Details) VALUES
('".$_POST['txtName']."','".$_POST['txtArea']."','".$_POST['txtDetails']."')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
答案 0 :(得分:1)
由于您选择了表单ID,因此您应该在前面使用#符号。
另外,在第一行使用e.preventDefault。
$(document).on('submit','#formReviews',function(e) {
e.preventDefault(); // Add it here
$.ajax({
url : $(this).attr('action'),
type : $(this).attr('method'),
data : $(this).serialize(),
success : function(html){
alert('Review Submitted');
}
});
});