I'm working on triggering a function through AJAX after clicking in a specific element, but it does not work.
Not even a simple echo "Test" works in the function, it just does not seem to run, yet the ajax call is executed and works. You can check in developer tools on this website https://woocommerce-842277-3644151.cloudwaysapps.com/
- Go to product page
- Add to cart
- On the page where the image of two football players are just click on the image somewhere and check the Network tab in Developer tools, the payload etc. is present.
This is my code
functions.php (enqueue and localize)
wp_enqueue_script( 'treblecars-ajaxapp', get_template_directory_uri() . '/js/ajaxapp.js', array(), _S_VERSION, true );
wp_localize_script( 'treblecars-ajaxapp', 'trblAjax', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );
ajaxapp.js
jQuery(document).ready(function($){
// Fill coords on active item and move to the next item
$('#botbSpotImage').click(function(e) {
var cart = []; // Will retrieve every cart item's meta
$('.botbSpotEvenWaCUnplayed').each(function(){
//This object will store your meta data and be pushed into kart array
var kitm = {
'p' : $(this).attr('data-product-id'),
'm' : $(this).find('input[name="coords_input"]').val(),
'k' : $(this).attr('data-entry-id')
};
cart.push(kitm);
});
$.ajax({
url: trblAjax.ajaxurl,
data: {
'action': 'update_cart_item_meta',
'k': cart
},
success:function(data){
console.log(data);
},
error:function(errorThrown){
console.log(errorThrown);
}
});
});
});
functions.php (actual function I want to run)
function update_cart_item_meta(){
global $woocommerce;
$cart = $woocommerce->cart->cart_contents;
$updt = Array();
foreach ($_REQUEST['k'] AS $item){
$product = new stdClass();
$updtCL = new stdClass();
$product->{'id'} = $item['p']; //This is product id
$product->{'mymeta'} = $item['m']; //This is metadata
$updtCL->{'krtkey'} = $item['k']; //This is product key in cart
$updtCL->{'meta'} = $product;
$updt[] = $updtCL;
}
// cycle the cart replace the meta of the correspondant key
foreach ($cart as $key => $item) {
foreach($updt as $updtitem){
if($key == $updtitem->krtkey){ // if this kart item corresponds with the received, the meta data is updated
// Update the content of the kart
$woocommerce->cart->cart_contents[$key]['coordinates'] = $updtitem->meta;
}
}
}
// This is the magic: With this function, the modified object gets saved.
$woocommerce->cart->set_session();
wp_die();
}
add_action('wp_ajax_update_cart_item_meta', 'update_cart_item_meta');
add_action('wp_ajax_nopriv_update_cart_item_meta', 'update_cart_item_meta');