我正在尝试进行ajax调用,以便在用户不必离开页面的情况下将项目添加到购物车。我已经设法编写了以下代码,但它没有任何效果。在addtocart.php上,我无情地输入ProdID
,size
和Category
,但没有回显。有人可以看看我的ajax和addtocart.php
AJAX
<script>
$(document).ready(function(){
$('.ajax').click(function(){
$.ajax({
url: '../main/php/addtocart.php',
type: 'post',
data:{
length:$('#length').val(),
Category:$('#Category').val(),
id:$('#id').val(),
Qty:$('#Qty').val()
},
success: function(data) {
}
});
});
});
</script>
PHP
<?php
include('dbconnect.php');
$id = $_POST['id'];
$length = $_POST["size"];
$qty = $_POST['Qty'];
$Category = $_POST['Category'];
$stmt = $conn->prepare("
SELECT ProductName, Category.Name, size, Price
FROM itembag, Product, Category
WHERE Product.ProdID =:id
AND size= :length AND Category.Name = :Category Limit 1");
$stmt->bindParam('id',$id);
$stmt->bindParam('length',$length);
$stmt->bindParam('Category',$Category);
$stmt->execute();
$i=0;
foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $row) {
if ($i == 0) {
echo 'status:1,id:'.$row['ProdID'].',Price:'.$row['Price'].',txt:\'\
\
<table width="100%" id="table_'.$row['ProdID'].'">\
<tr>\
<td width="60%">'.$row['ProductName'].'</td>\
<td width="40%">$'.$row['Price'].'</td>\
<td width="10%">$'.$row['Category'].'</td>\
</tr>\
</table>\'';
}
}
?>
附加信息:一个项目可能有1个ID,但它有不同的大小和许多类别。
答案 0 :(得分:1)
缺少POST的数据
data: {
//Here you have to put your data
},
您必须获得要POST的值 例如:
('.ajax').click(function(){
pid = $('#pid').val();//#pid->is the id of your input, the same bellow
length = $('#length').val();
Qty = $('#Qty').val();
Category = $('#Category').val();
$.ajax({
url: '../main/php/addtocart.php',
data:{
pdi:pdi,
length:length,
Qty :Qty ,
Category : Category},
type: 'post',
}).done(function(data) {
$(data).html('#containerShoppingCart');//Callback Replace the html of your shoppingCart Containe with the response of addtocart.php
}).fail(function(){ alert("failed!"); });//Some action to indicate is Failing
您可以看到http://api.jquery.com/jQuery.ajax/以获取更多信息
答案 1 :(得分:1)
根据您的HTML
,您的AJAX
会是这样的:
注意:如果您使用AJAX
,则必须id
而不是name
<强> AJAX 强>
$(document).ready(function()
{
$('#button').click(function()
{
var id = $('#id').val();
var length = $('#length').val();
var qty = $('#Qty').val();
var cat = $('#Category').val();
$.ajax({
url: '../main/php/addtocart.php',
type: 'POST',
data: { id:id, length:length, qty:qty, cat:cat },
success: function(data)
{
//whatever you want to do
}
})
});
});
如果您在PHP
if(isset($_POST['id']) && isset($_POST['length']) && isset($_POST['Qty']) && isset($_POST['cat']))
{
$id = $_POST['id'];
$length = $_POST['length'];
$qty = $_POST['Qty'];
$Category = $_POST['Category'];
答案 2 :(得分:0)
使用jQuery加载可能会帮助您加载/更新购物车。 http://api.jquery.com/load/