我正在努力使用Ajax和PHP来创建购物车。目前我在console.log中可以看到当我点击“添加购物车”时正在选择正确的产品ID,但是当我尝试和var转储应该发送的POST数据时,我的PHP没有任何反应。我需要能够在PHP中获取该产品ID,在数据库中搜索产品,然后添加到购物篮中。
PHP
<?php
session_start();
include('classes/class-database-functions.php');
$database = new Database_Functions();
if($_POST) {
var_dump($_POST);
}
?>
JS
$(document).ready(function(){
$(".form-item").submit(function(e){
var form_data = $(this).serialize();
var button_content = $(this).find('button[type=submit]');
button_content.html('Adding...'); //Loading button text
$.ajax({ //make ajax request to cart_process.php
url: "cart_process.php",
type: "POST",
dataType:"json", //expect json value from server
data: form_data
}).done(function(data){ //on Ajax success
$("#cart-info").html(data.items); //total items in cart-info element
button_content.html('Add to Cart'); //reset button text to original text
alert("Item added to Cart!"); //alert user
if($(".shopping-cart-box").css("display") == "block"){ //if cart box is still visible
$(".cart-box").trigger( "click" ); //trigger click to update the cart box.
}
})
e.preventDefault();
});
});