我在尝试显示“结果”时遇到了困难。消息没有被重定向到insert.php文件。结果'消息应显示而不重新加载。请帮忙。非常感谢。
html代码
<html>
<head>
<title>PHP AJAX TUTORIAL</title>
</head>
<body>
<h1>Enter Product</h1>
<form method = 'post' action = 'insert.php'>
<input type = "text" id = "n" name = "productname" placeholder = "Product name"></br>
<input type = "text" id = "b" name = "brandname" placeholder = "Brand name"></br>
<input type = "number" id = "q" name = "quantity" placeholder = "Quantity"></br>
<button>Save Product</button>
</form>
<p id = "result"></p>
<script type="text/javascript" src="js/jquery-3.2.1.min"></script>
<script type="text/javascript" src="js/script.js"></script>
</body>
</html>
insert.php
<?php
// The browser (HTML) sends inforamtion to the server(php) using $_POST
$name = $_POST['productname']; //'productname' is from html input
$brand = $_POST['brandname']; //'brandname' is from html input
$quantity = $_POST['quantity']; //'quantity' is from html input
$con = new mysqli ('localhost', 'root', '', 'tutorial');
if ($con -> connect_error) {
echo 'database connect error';
}
//Prepare statement to insert into database
$stmt = $con -> prepare ("INSERT into products(name, brand, quantity) VALUES (?, ?, ?)");
// Bind the variables to the values
$stmt -> bind_param ("ssi", $name, $brand, $quantity);
//Execute
if($stmt -> execute()){
echo "success";
}
else {
echo "failure";
}
?>
的script.js
$(document).ready(function(){
$('form').submit(function(e){
e.preventDefault();
$.post(
'insert.php',
{
productname:$('#n').val(),
brandname:$('#b').val(),
quantity:$('#q').val()
}
function(result){
if (result == "success"){
$('#result').html("Values inserted successfully");
}
else{
$('#result').html("Error!");
}
}
);
});
});