I'm submitting an add to cart action in WooCommerce using the following jQuery code:
jQuery(document).ready(function($) {
$('form').submit(function() {
$theForm = $(this);
url = $theForm.attr('action');
// send xhr request
$.ajax({
type: $theForm.attr('method'),
url: $theForm.attr('action'),
data: $theForm.serialize(),
success: function(data) {
console.log('Yay! Form sent.');
}
});
// prevent submitting again
return false;
});
});
Which works great on variable products but single products does nothing. It seems to be that the way the simple product form is shown differs from the variable form and posts in a different way.
If I replace the simple.php button code with the button code from variable-add-to-cart-button.php then the ajax works fine. But what is the proper way to deal with this case?
Update
There are no errors in the console. However, checking the Ajax requests shows that for a variable product form (which works fine) this is the data:
attribute_ticket-type:Adult+(11%2B+Years)
wc_deposit_option:no
start_date:31+December%2C+2018
start_date_submit:2018-12-31
end_date:
end_date_submit:
_wceb_nonce:901daca64c
quantity:1
add-to-cart:12223
product_id:12223
variation_id:12229
...but for the simple product page this is reported (notice missing product ID and add-to-cart id etc)
start_date:4 August, 2017
start_date_submit:2017-08-04
end_date:
end_date_submit:
_wceb_nonce:901daca64c
wc_deposit_option:no
quantity:1
This explains why no action is recorded as there is no ID to record it against. If I add the following hidden input to the button on the simple product page it works:
<input type="hidden" name="add-to-cart" value="<?php echo absint( $product->get_id() ); ?>" />
Is this what I should be doing though or is there a better more standard way to deal with this. Thanks.