It is not a plugin, it is just a simple file call on ajax.
我的Js代码
$(\'.pkg-btn\').click(function(){
var this_id = $(this).parent().attr(\'id\');
var url = templateUrl+\'/tw-add-to-cart-ajax.php\';
$.ajax({
type: \'POST\',
url: url,
data: ({selected_package_id: this_id}),
dataType: \'json\',
success: function(data1) {
console.log(data1);
$(\'#conditions\').show();
}
});
});
我的php文件代码
<?php
// $product_id = $_POST[\'selected_package_id\'];
// echo $product_id; // It displays id - works fine here
// exit();
add_action(\'woocommerce_add_to_cart\', \'custome_add_to_cart\');
function custome_add_to_cart() {
echo \'hook called\'; // This is not showing any message
exit();
global $woocommerce;
$product_id = $_POST[\'selected_package_id\'];
echo $product_id; // This is not displaying id
exit();
$found = false;
//check if product already in cart
if ( sizeof( WC()->cart->get_cart() ) > 0 ) {
foreach ( WC()->cart->get_cart() as $cart_item_key => $values ) {
$_product = $values[\'data\'];
if ( $_product->id == $product_id )
$found = true;
}
// if product not found, add it
if ( ! $found ){
WC()->cart->add_to_cart( $product_id );
}
} else {
// if no products in cart, add it
WC()->cart->add_to_cart( $product_id );
}
}
在调用hook之前,我在php文件中获得传递的id并对其进行回显。它显示id,意味着js将数据传递给php,php也会获得该id,但当我调用hook时,它显示错误:
jquery-3.4.1.min.js:2 POST domain-url/wp-content/themes/my-theme-folder/tw-add-to-cart-ajax.php 500 (Internal Server Error) 并在网络中显示消息
This request has no response data available