不确定我遗失了什么,但是我的代码即将尝试构建时遇到一些问题。
HTML
<form action="response.php" method="post" id="add_product">
<input type="hidden" name="action" value="add_product">
<div class="row">
<div id="response" class="alert alert-success" style="display:none;">
<a href="#" class="close" data-dismiss="alert">×</a>
<div class="message"></div>
</div>
<div class="col-xs-4">
<input type="text" class="form-control" id="product_name" placeholder="Enter product name">
</div>
<div class="col-xs-4">
<input type="text" class="form-control" id="product_desc" placeholder="Enter product description">
</div>
<div class="col-xs-4">
<div class="input-group">
<span class="input-group-addon"><?php echo CURRENCY ?></span>
<input type="text" id="product_price" class="form-control" placeholder="0.00" aria-describedby="sizing-addon1">
</div>
</div>
</div>
<div class="row">
<div class="col-xs-12 margin-top btn-group">
<input type="submit" id="action_add_product" class="btn btn-success float-right" value="Add product" data-loading-text="Adding...">
</div>
</div>
RESPONSE.PHP
//check if any connection error was encountered
if(mysqli_connect_errno()) {
echo "Error: Could not connect to database.";
exit;
}
$action = isset($_POST['action']) ? $_POST['action'] : "";
// Adding new product
if($action == 'add_product') {
$data = $_POST['serialize']; // serialize the data
$product_name = $data['product_name'];
$product_desc = $data['product_desc'];
$product_price = $data['product_price'];
//our insert query query
$query = "INSERT INTO products SET
product_name = '".$product_name."',
product_desc = '".$product_desc."',
product_price = '".$product_price."'
";
//execute the query
if($mysqli -> query($query)) {
//if saving success
echo "User was created.";
} else {
//if unable to create new record
echo "Database Error: Unable to create record.";
}
//close database connection
$mysqli -> close();
}
scripts.js中
// add product
$('#action_add_product').click(function(){
var $btn = $(this).button('loading');
$.ajax({
url: 'response.php',
type: 'POST',
data: $('#add_product').serialize(),
success: function(result){
$('#response .message').html('Product has been added successfully!');
$('#response').fadeIn();
$btn.button('reset');
}
});
});
答案 0 :(得分:0)
点击 #action_add_product 按钮后,您的表单即会提交。如果你想使用ajax,你可以:
button
更改为a
- 这会阻止您的表单被提交$('#action_add_product').click(function(){
更改为以下内容:$('#add_product').submit(function(e){
e.preventDefault();