当我包含$ .post jQuery代码时,产品信息不会插入到数据库中。但是,当我删除$ .post jQuery代码时,产品已成功插入数据库。请帮助。
的index.html
<html>
<body>
<h1>Enter Product Details</h1>
<form id = "product_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 id = "save_button">Save information</button>
</form>
<p id = "result"></p>
<button id = "btn">Test Button</button>
<script type = "text/javascript" src = "js/jquery.js"></script>
<script type = "text/javascript" src = "js/script.js"></script>
</body>
</html>
insert.php
<?php
$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(){
$('#btn').click(function(){
alert();
});
//The problem code!!!!
$('#product_form').submit(function(event){
event.preventDefault();
$.post(
'insert.php',
{
productname:$("#n").val(),
brandname:$("#b").val(),
value:$("#q").val(),
},
function(result){
if(result == "success"){
$("#result").html("Values inserted successfully!");
}
else{
$("#result").html("Error!");
}
}
);
});
});
答案 0 :(得分:1)
在$ .post的第二个参数中设置要发送到服务器的数据,你有
{
productname:$("#n").val(),
brandname:$("#b").val(),
value:$("#q").val()
}
因此,您需要将value:
更改为quantity:
,以便让ajax提交与传统表单提交相匹配。