我有一个文件cart.html,它显示从数据库中提取的项目列表,每个项目都有一个按钮' AddToCart'单击时调用函数addDB()并将产品添加到表product_add。 我的问题是当按钮“AddToCart'单击只有nulll值插入表product_add。
//This function is found in the cart.html and get the items from the database
$(document).ready(function() {
$("#product").click(function() {
$.ajax({ //create an ajax request to load_page.php
type: "GET",
url: "allProducts.php",
dataType: "html", //expect html to be returned
success: function(response){
$("#responsecontainer").html(response);
//alert(response);
}
});
});
});
//the above function is called when a button 'View All Products' is clicked
<input type="button" id="cart" value="View Cart"/>
上面的代码工作正常并显示结果
//These lines of codes are in the allProducts.php
echo "<tr>";
echo "<td>".$row['id']."</td>";
echo "<td><img src=".$row['image']." width='120' height='100'/></td>";
echo "<td>".$row['name']."</td>";
echo "<td>".$row['price']."</td>";
echo "<td>";
echo "<input type='button' value='Add to Cart' onclick='addDB()'/>";
echo "</td>";
echo "</tr>";
这是函数addDB()
function addDB() {
var request = $.ajax({
url: "add.php",
type: "GET",
dataType: "html"
});
request.fail(function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus );
});
};
这是add.php
<?php
include 'dbConnect.php';
$id = isset($_GET['id']) ? $_GET['id'] : "";
$name = isset($_GET['name']) ? $_GET['name'] : "";
$price= isset($_GET['price']) ? $_GET['price'] : "";
$insert = "INSERT INTO product_add(id, name, price) VALUES ('$id', '$name','$price')";
$insertQuery=mysql_query($insert);
?>
我的问题是,当点击按钮&#39; AddToCart时,&#39; null或0正在数据库中插入。有人可以帮帮我吗?
答案 0 :(得分:1)
您没有向php页面发送任何数据。一个简单的方法是通过AJAX-Call的URL中的GET-Parameters传递它们:
function addDB(id, name ,price) {
var request = $.ajax({
url: "add.php?id=" + id + "&name=" + name + "&price=" + price,
type: "GET"
});
request.done(function() {
alert("Ajax call done.");
});
}
此外,您的代码容易受到sql-injections的攻击。请始终使用prepared statements
您修改后的add.php将如下所示:
<?php
include 'dbConnect.php';
$id = isset($_GET['id']) ? $_GET['id'] : "";
$name = isset($_GET['name']) ? $_GET['name'] : "";
$price= isset($_GET['price']) ? $_GET['price'] : "";
$query = $mysqli->prepare("INSERT INTO product_add(id, name, price) VALUES (?, ?, ?)");
$query->bind_param("isi", $id, $name, $price);
$query->execute();
$query->close();
?>
你当然必须初始化对象&#34; $ mysqli&#34;不知何故,在你的文件dbConnect.php中使用它。